package com.yuanfeng.goods.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.DealerGoodsUserInfoDTO;
import com.yuanfeng.commoms.dto.goods.*;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.dto.shop.ShopIndexDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.rocketmq.MqSendUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.excel.Constants;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.*;
import com.yuanfeng.commoms.vo.base.*;
import com.yuanfeng.commoms.vo.goods.*;
import com.yuanfeng.commoms.vo.goodscat.GoodsCatSearchChildVO;
import com.yuanfeng.commoms.vo.goodscat.WebCatMenuVO;
import com.yuanfeng.commoms.vo.order.DealerOrderGoodsVO;
import com.yuanfeng.commoms.vo.shop.*;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.commoms.vo.user.UserPermissionsVO;
import com.yuanfeng.goods.dto.*;
import com.yuanfeng.goods.entity.*;
import com.yuanfeng.goods.feign.*;
import com.yuanfeng.goods.mapper.*;
import com.yuanfeng.goods.service.GoodsCommonService;
import com.yuanfeng.goods.vo.VoucherMessageVO;
import com.yuanfeng.goods.vo.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


/**
 * @ClassName GoodsCommonServiceImpl
 * @Description 商品表
 * @Author cyp
 * @Date 2023-05-25 09:16:35
 * @Version 1.0
 **/
@Service
public class GoodsCommonServiceImpl extends ServiceImpl<GoodsCommonMapper, GoodsCommonEntity>
        implements GoodsCommonService {
    private static final String PATTERN = "\n\t(.*?)</p>";
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private BusinessServiceClient businessServiceClient;
    @Autowired
    private OrderServiceClient orderServiceClient;
    @Autowired
    private ActivityServiceClient activityServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;
    @Resource
    private GoodsImagesMapper goodsImagesMapper;
    @Resource
    private GoodsBaseMapper goodsBaseMapper;
    @Resource
    private GoodsUserFootprintMapper goodsUserFootprintMapper;
    @Resource
    private GoodsCommonDetailMapper goodsCommonDetailMapper;
    @Resource
    private GoodsCommonAttributeAssociationMapper goodsCommonAttributeAssociationMapper;
    @Resource
    private GoodsAttributeMapper goodsAttributeMapper;
    @Resource
    private GoodsAttributeContentMapper goodsAttributeContentMapper;
    @Resource
    private GoodsCatMapper goodsCatMapper;
    @Resource
    private GoodsCommonMapper goodsCommonMapper;
    @Resource
    private GoodsDealerPutawayRecordMapper goodsDealerPutawayRecordMapper;
    @Resource
    private ActivityNoneGoodsMapper activityNoneGoodsMapper;
    @Resource
    private GoodsPropertyMapper goodsPropertyMapper;
    @Resource
    private GoodsSpecValueMapper goodsSpecValueMapper;
    @Resource
    private GoodsSpecMapper goodsSpecMapper;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    private static final Logger logger = LoggerFactory.getLogger(GoodsCommonServiceImpl.class);
    @Override
    public ResponseResult queryGoodsDetail(GoodsDetailsDTO param) {
        //查看plus状态
        Integer selectplus = (Integer) baseServiceClient.queryMerchantPlusRule().getData();

        GdsDetailPageResultVO detailPage = new GdsDetailPageResultVO();
        //获取用户信息
        ObjectMapper mapper = new ObjectMapper();
        // 获取user信息
        UserInfoVO userinfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.getToken());
        String userId = null;
        if (null != userinfo) {
            userId = userinfo.getUserId();
        }


        // 查询商品详情
        GdsBaseDetailResultVO goodsBases = this.baseMapper.selectByGoodsId(param.getGoodsId());
        if (null == goodsBases) {
            return ResponseResult.fail(2, "商品不存在");
        }
//        if (goodsBases != null && goodsBases.getGoodsType() == 2){
//            return  ResponseResult.fail(0, "温馨提示：供应商商品仅支持在电脑端查看~");
//        }
        //设置plus折扣
        if (userinfo != null) {
            goodsBases.setPlusMember(userinfo.getPlusMember());
            goodsBases.setPlusDiscount(userinfo.getPlusDiscount());
        }

        if (goodsBases.getGoodsMaxSale().equals(0)) {
            goodsBases.setGoodsMaxSale(goodsBases.getGoodsStock());
        }
        if (!goodsBases.getGoodsIsShelves().equals(1) || !goodsBases.getCommonState().equals(1)
                || !goodsBases.getCommonVerify().equals(1)) {
            goodsBases.setGoodsStock(0);
        }
        if (StringUtils.isNotEmpty(goodsBases.getSpecValue())) {
            List<GoodBaseSpecValuesJsonBeanVO> specValuesJsonBeans = new ArrayList<>();
            JSONArray specValuesJsonBeanArray = com.alibaba.fastjson.JSONObject.parseArray(goodsBases.getSpecValue());
            for (int index = 0; index < specValuesJsonBeanArray.size(); index++) {
                com.alibaba.fastjson.JSONObject obj = specValuesJsonBeanArray.getJSONObject(index);
                GoodBaseSpecValuesJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), GoodBaseSpecValuesJsonBeanVO.class);
                specValuesJsonBeans.add(temp);
            }
            goodsBases.setSpecValueList(specValuesJsonBeans);
        }
        Integer commonId = goodsBases.getCommonId();
        Integer shopId = goodsBases.getShopId();
        Integer result = 0;
        Map<String, Object> paramTmp = new HashMap<>();
        paramTmp.put("shopId", shopId);
        InvoiceSwitchEntityVO data = businessServiceClient.queryShopInvoiceSwitch(paramTmp);
        if (null != data) {
            Integer invoiceSwitchStatus = data.getInvoiceSwitchStatus();
            Integer invoiceAuditStatus = data.getInvoiceAuditStatus();
            if (1 == invoiceAuditStatus && 1 == invoiceSwitchStatus) {
                result = 1;
            } else if (1 == invoiceAuditStatus && 0 == invoiceSwitchStatus) {
                result = 1;
            }
        }


        Integer catId = null;

        if (null != goodsBases) {
            detailPage.setShopGate(0);
            GdsShopDetailResultVO shopDetail = this.businessServiceClient.queryShopinfoByShopId(shopId);
            //判断是否为该商铺的门店账号
            if (null != userinfo) {
                Map<String, String> map = new HashMap<>();
                map.put("userMobile",userinfo.getUserMobile());
                Integer phoneShopId = businessServiceClient.queryUserIsGate(map);
                if (phoneShopId != null) {
                    if (phoneShopId.equals(shopDetail.getShopId())) {
                        detailPage.setShopGate(1);
                    }
                }
            }

            if (shopDetail != null) {
                // 设置店铺默认值
                shopDetail.setInvoiceActive(result);
                setShopDefaultValue(goodsBases, shopDetail);
            }
            // 查询公共信息
            GdsCommonResultVO gdsCommon = this.baseMapper.selectTransport(commonId);
            if (StringUtils.isNotEmpty(gdsCommon.getSpecParam())) {
                List<SpecParamJsonBeanVO> list = new ArrayList<>();
                JSONArray jsonSpecParam = com.alibaba.fastjson.JSONObject.parseArray(gdsCommon.getSpecParam());
                for (int index = 0; index < jsonSpecParam.size(); index++) {
                    com.alibaba.fastjson.JSONObject obj = jsonSpecParam.getJSONObject(index);
                    SpecParamJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), SpecParamJsonBeanVO.class);
                    list.add(temp);
                }
                gdsCommon.setSpecParamList(list);
            }
            //如果商品未参加活动商品原价就是市场价，否则商品活动价即为商品销售价 原商品销售价赋值为商品市场价
            if(null != goodsBases.getCommonIsXian() && 0 != goodsBases.getCommonIsXian()){
                goodsBases.setGoodsMarketPrice(goodsBases.getGoodsPrice());
            }
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity2(goodsBases.getGoodsId(),goodsBases.getGoodsStock(),
                    goodsBases.getGoodsMaxSale(), commonId, goodsBases.getCommonIsXian(), userId, param.getSessionTime());

            if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
                goodsBases.setActivityStatus(activityGoodsDetail.getActivityStatus());
                goodsBases.setActivityGoodsDetailDTO(activityGoodsDetail);
                goodsBases.setCurrentCartQuantity(activityGoodsDetail.getCurrentCartQuantity());
                if (!activityGoodsDetail.getActivityStatus().equals(4)) {
                    goodsBases.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                    goodsBases.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());
                }
                //满减赠折活动展示活动内容ZZZ
                if (activityGoodsDetail.getActivityStatus().equals(5)) {
                    String promotionContent = "";
                    List<ManjianzengzhePromotionContentQueryResultVO> promotionContents = activityServiceClient.selectReductionPolicyPromotionContent(commonId);
                    for (ManjianzengzhePromotionContentQueryResultVO r : promotionContents) {
                        Integer discountType = r.getDiscountType();
                        Integer hasGiveaway = r.getHasGiveaway();
                        String discountContent = r.getDiscountContent();
                        boolean mzFlag = discountContent == null || "".equals(discountContent);
                        //满减赠
                        if (discountType == 1) {
                            if (null == goodsBases.getPromotionType() || "".equals(goodsBases.getPromotionType())) {
                                if (hasGiveaway == 1 && mzFlag) {
                                    goodsBases.setPromotionType("满赠");
                                } else {
                                    goodsBases.setPromotionType("满减");
                                }
                            }
                            //满折
                        } else if (discountType == 3) {
                            goodsBases.setCommonIsXian(6);
                            goodsBases.setActivityStatus(6);
                            goodsBases.setPromotionType("满折扣");
                        }
                        if ("满减".equals(goodsBases.getPromotionType()) && hasGiveaway == 1) {
                            goodsBases.setPromotionType("满减赠");
                        } else if ("满赠".equals(goodsBases.getPromotionType()) && !mzFlag) {
                            goodsBases.setPromotionType("满减赠");
                        }
                        dealPromotionContent(r);

                        promotionContent = promotionContent + r.getPromotionContent() + "\n";

                    }
                    goodsBases.setPromotionContent(promotionContent);


                }
            }
            catId = gdsCommon.getCatId();

            // 查询图片信息
            List<GdsImageDetailResultVO> goodsImages = goodsImagesMapper.selectByCommonId(param.getGoodsId(),
                    shopId);
            if (CollectionUtils.isEmpty(goodsImages)) {
                GdsImageDetailResultVO goodsImage = new GdsImageDetailResultVO();
                goodsImage.setImagesImage(gdsCommon.getCommonImage());
                goodsImage.setImagesDisplayorder(0);
                goodsImage.setImagesIsDefault(1);
                goodsImages.add(goodsImage);
            }
            // 处理结果
            detailPage.setGoodsBases(goodsBases);
            detailPage.setGoodsImages(goodsImages);
            detailPage.setShopDetail(shopDetail);
            detailPage.setGdsCommon(gdsCommon);

            // 处理供应商商品
            if (null != goodsBases.getGoodsType() && goodsBases.getGoodsType() == 2) {
                BaseGoodsConfigVO manageGdsGoodsConfig = goodsBaseMapper.queryDelayGoodsConfig(goodsBases.getCommonId());
                detailPage.setManageGdsGoodsConfig(manageGdsGoodsConfig);
                if (manageGdsGoodsConfig != null) {
                    if (null == userinfo) {
                        goodsBases.setOperateType2(manageGdsGoodsConfig);
                    } else {
                        if (manageGdsGoodsConfig.getSellCheck() == 1) {
                            // 需要经销审核
                            DealerGoodsUserInfoDTO goodsUserInfo = new DealerGoodsUserInfoDTO(goodsBases.getShopId(), userinfo.getShopId());
                            goodsUserInfo.setDealerStatus(CommonType.supplierGoodsStatus.AUTH_PASS.getCode());
                            DealerApplyInfoVO dealerApplyInfo = baseServiceClient.queryDealerApplyByShop(goodsUserInfo);
                            if (null == dealerApplyInfo) {
                                goodsBases.setOperateType(CommonType.supplierGoodsStatus.APPLY.getCode());
                            }
                        }
                        if (null == goodsBases.getOperateType()) {
                            // 一键上架商品判断商品是否已经销
                            if (manageGdsGoodsConfig.getSellDeliver() == 1) {
                                Integer dealerGoodsIdCount = goodsBaseMapper.queryGoodsDealerInfo(userinfo.getShopId(), goodsBases.getGoodsId());
                                if (null != dealerGoodsIdCount) {
                                    goodsBases.setOperateType(CommonType.supplierGoodsStatus.HAVA_GOODS.getCode());
                                } else {
                                    goodsBases.setOperateType(CommonType.supplierGoodsStatus.PUTAWAY.getCode());
                                }
                            } else {
                                goodsBases.setOperateType(CommonType.supplierGoodsStatus.BUY.getCode());
                            }
                        }
                    }
                }
            }
        }
        detailPage.setPlusStatus(selectplus);

        // 更新点击量
        goodsBaseMapper.updateGoodsClick(param.getGoodsId());
        this.baseMapper.updateGoodsClick(commonId);

        // 添加足迹
        if (null != userinfo) {
            addUserFoot(userinfo, commonId, catId);
        }

        return ResponseResult.success(detailPage);
    }

    @Override
    public void addUserFoot(UserInfoVO userinfo, Integer commonId, Integer catId) {
        WapUserFootPrintAddParamDTO userFoot = new WapUserFootPrintAddParamDTO();
        // 获取用户id
        String userId = userinfo.getUserId();
        // 查询商品是否已添加到足迹
        FkgouUserFootprintDTO selectByUserId = goodsUserFootprintMapper.selectByUserId(userId, commonId);
        if (selectByUserId == null) {
            userFoot.setUserId(userId);
            userFoot.setCatId(catId);
            userFoot.setFootprintDate(DateUtils.getDate());
            userFoot.setFootprintTime(DateUtils.getNowDateToString());
            userFoot.setCommonId(commonId);
            goodsUserFootprintMapper.addUserFoot(userFoot);
        } else {
            selectByUserId.setFootprintDate(DateUtils.getDate());
            selectByUserId.setFootprintTime(DateUtils.getNowDateToString());
            goodsUserFootprintMapper.updateUserFoot(selectByUserId);
        }

    }

    private void setShopDefaultValue(GdsBaseDetailResultVO goodsBases, GdsShopDetailResultVO shopDetail) {
        if (shopDetail.getShopLogo() == null || shopDetail.getWapShopLogo() == null) {
            String configValue = baseServiceClient.selectConfigValueFeign("logo_copywriting_ico_shop");
//			ShopConfigDefaultValue shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValue.class);

            if (shopDetail.getShopLogo() == null) {
                shopDetail.setShopLogo(configValue);
            }
            if (shopDetail.getWapShopLogo() == null) {
                shopDetail.setWapShopLogo(configValue);
            }
        }
        Map<String,BigDecimal> shopEvaluation = this.baseMapper.selectShopEvaluation(shopDetail.getShopId());
        BigDecimal evaluation = BigDecimal.ZERO;
        for (BigDecimal num : shopEvaluation.values()) {
            evaluation = evaluation.add(num); // 将每个元素累加到sum变量中
        }
        shopDetail.setOverallScore(Double.parseDouble(evaluation.divide(new BigDecimal(3),2, RoundingMode.HALF_UP).toString()));
        // 查询商品数量
        Integer shopCount = this.baseMapper.selectByShopId(goodsBases.getShopId());
        shopDetail.setShopCount(shopCount);
    }

    @Override
    public ActivityGoodsDetailDTO dealActivity2(Integer goodsId, Integer goodsStock, Integer goodsMaxSale, Integer commonId, Integer commonIsXian, String userId, Date sessionTime) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        Integer currentCartQuantity = 0;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣
        if (!commonIsXian.equals(0)) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(2)) {
                if (null != userId) {
                    //查询当前商品在购物车的数量
                    currentCartQuantity = orderServiceClient.selectCurrentCartQuantity(userId, goodsId);
                }
                // 秒杀
                commonIsXian = dealSeckillActivity1(commonId,goodsId, goodsStock, commonIsXian, activityGoodsDetail, sessionTime);
            } else if (commonIsXian.equals(3)) {
                if (null != userId) {
                    //查询当前商品在购物车的数量
                    currentCartQuantity = orderServiceClient.selectCurrentCartQuantity(userId, goodsId);
                }
                // 限时折扣
                commonIsXian = dealDiscountActivity(goodsId, goodsMaxSale, commonIsXian, activityGoodsDetail);
            } else if (commonIsXian.equals(4)) {
                // 拼团
                commonIsXian = dealPintuanActivity(commonId, commonIsXian, goodsId, activityGoodsDetail);
            } else if (commonIsXian.equals(5)) {
                //满减赠折
                commonIsXian = dealManjianzengzheActivity(commonId, goodsMaxSale, commonIsXian, goodsId, activityGoodsDetail);

            }
            activityGoodsDetail.setActivityStatus(commonIsXian);
            activityGoodsDetail.setCurrentCartQuantity(currentCartQuantity);
        }

        return activityGoodsDetail;

    }

    public Integer dealSeckillActivity1(Integer commonId,Integer goodsId, Integer goodsStock, Integer commonIsXian,
                                         ActivityGoodsDetailDTO activityGoodsDetail, Date sessionTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("commonId",commonId);
        map.put("goodsId",goodsId);
        map.put("sessionTime",sessionTime);
        AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId(map);
        if (null != seckillGoods) {
            if (DateUtils.compareDate2(seckillGoods.getGoodsEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsEndTime());
                activityGoodsDetail.setActivityEndTime(seckillGoods.getGoodsEndTime());
                // 判断是否开始
                if (DateUtils.compareDate2(seckillGoods.getGoodsStartTime())) {
                    activityGoodsDetail.setActivityStartStatus(0);
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsStartTime());
                } else {
                    activityGoodsDetail.setActivityStartStatus(1);
                }
                // 设限
                if (!seckillGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(seckillGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                // 设限
                if (!seckillGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(0);
                }
                if(seckillGoods.getSeckillNum() != null && seckillGoods.getSeckillNum() < goodsStock){
                    activityGoodsDetail.setGoodsStock(seckillGoods.getSeckillNum());
                }else{
                    activityGoodsDetail.setGoodsStock(goodsStock);
                }

                activityGoodsDetail.setCommonStock(seckillGoods.getSeckillNums() != null ? seckillGoods.getSeckillNums() : 0);
                activityGoodsDetail.setDiscountTitle(seckillGoods.getSeckillTitle());
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(seckillGoods.getSeckillPrice());
                activityGoodsDetail.setActivityStartTime(seckillGoods.getGoodsStartTime());
            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    private Integer dealDiscountActivity(Integer goodsId, Integer goodsMaxSale, Integer commonIsXian,
                                         ActivityGoodsDetailDTO activityGoodsDetail) {
        AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsId(goodsId);
        Long overplusTime = null;
        if (null != discountGoods) {
            Integer discountState = discountGoods.getDiscountGoodsState();
            if (DateUtils.compareDate2(discountGoods.getGoodsEndTime())) {
                activityGoodsDetail.setActivityEndTime(discountGoods.getGoodsEndTime());
                activityGoodsDetail.setActivityStartStatus(discountState);
                activityGoodsDetail.setDiscountAmount(discountGoods.getDiscountAmount());
                activityGoodsDetail.setDiscountTitle(discountGoods.getDiscountTitle());
                activityGoodsDetail.setActivityStartTime(discountGoods.getGoodsStartTime());
                //活动已经开始
                if (null != discountState && 1 == discountState) {
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), discountGoods.getGoodsEndTime());
                }//活动正在预热
                else if (null != discountState && 4 == discountState) {
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), discountGoods.getGoodsStartTime());
                }

                // 设限
                if (!discountGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(discountGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                if (!discountGoods.getDiscountUpperTime().equals(0)) {
                    activityGoodsDetail.setDiscountUpperTime(discountGoods.getDiscountUpperTime());
                } else {
                    activityGoodsDetail.setDiscountUpperTime(0);
                }
                // 设限
                if (!discountGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(discountGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(0);
                }
                activityGoodsDetail.setGoodsBuyCount(
                        discountGoods.getGoodsBuyCount() != null ? discountGoods.getGoodsBuyCount() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(discountGoods.getDiscountPrice());
            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    private Integer dealPintuanActivity(Integer commonId, Integer commonIsXian, Integer goodsId,
                                        ActivityGoodsDetailDTO activityGoodsDetail) {
        AppPintuanGoodsQueryResultVO pintuanGoods = activityServiceClient.selectpiecingTogetherByGoodsId(commonId, goodsId);
        if (null != pintuanGoods) {
            if (DateUtils.compareDate2(pintuanGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), pintuanGoods.getEndTime());
                activityGoodsDetail.setActivityEndTime(pintuanGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setPintuanPrice(pintuanGoods.getPrice());
                activityGoodsDetail.setPriceOne(pintuanGoods.getPriceOne());
                activityGoodsDetail.setActivityPrice(pintuanGoods.getPrice());
            } else {
                commonIsXian = 0;
            }
            pintuanGoods.setCommonIsXian(commonIsXian);
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }

    private Integer dealManjianzengzheActivity(Integer commonId, Integer goodsMaxSale, Integer commonIsXian, Integer goodsId,
                                               ActivityGoodsDetailDTO activityGoodsDetail) {
        ManjianzengzheGoodsQueryResultVO manjianzengzheGoods = activityServiceClient.selectReductionPolicyByGoodsId(commonId);
        if (null != manjianzengzheGoods && null != manjianzengzheGoods.getPromotionId()) {
            if (DateUtils.compareDate2(manjianzengzheGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), manjianzengzheGoods.getEndTime());
                activityGoodsDetail.setActivityEndTime(manjianzengzheGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                List<ManjianzengzheGoodsRuleQueryDTO> ruleList = activityServiceClient.selectReductionPolicyRuleDetailList(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setPromotionId(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setRuleList(ruleList);
                activityGoodsDetail.setMjzzPrice(manjianzengzheGoods.getGoodsPrice());
                activityGoodsDetail.setGoodsLowerLimit(0);
                activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);

            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }

    /**
     * 生成活动内容
     * 1. 若活动类型为满减,discountType=1:
     * 1.1 若hasGiveaway=0,无赠品:
     * 活动内容为:单笔满¥meetAmount，立减现金¥discountContent
     * 1.2 若hasGiveaway=1,有赠品:
     * 1.2.1 discountContent不为空:
     * 活动内容为:单笔满¥meetAmount，立减现金¥discountContent,送礼品giveawayName
     * 1.2.2 discountContent为空:
     * 活动内容为:单笔满¥meetAmount，送礼品giveawayName
     * 2. 若活动类型为满折,discountType=3:
     * 活动内容为:单笔订单满meetAmount件，立减折扣discountContent%
     *
     * @param r
     * @return
     */
    @Override
    public void dealPromotionContent(ManjianzengzhePromotionContentQueryResultVO r) {
        Integer discountType = r.getDiscountType();
        BigDecimal meetAmount = r.getMeetAmount();
        Integer hasGiveaway = r.getHasGiveaway();
        String discountContent = r.getDiscountContent();
        Integer giveawayId = r.getGiveawayId();
        StringBuilder promotionContent = new StringBuilder();
        //满减赠活动
        if (null != discountType && 1 == discountType) {
            //有赠品
            if (null != hasGiveaway && 1 == hasGiveaway) {
                GdsDetailsCommonQueryResultVO queryResult = this.baseMapper.selectByCommonId(giveawayId);
                String giveawayName = queryResult.getCommonName();
                String giveawayImage = queryResult.getCommonImage();
                //满减内容不为空
                //活动内容:单笔满¥meetAmount，立减现金¥discountContent,送礼品giveawayName
                if (null != discountContent && !"".equals(discountContent)) {
                    promotionContent.append("满");
                    promotionContent.append(meetAmount);
                    promotionContent.append("元减");
                    promotionContent.append(discountContent);
                    promotionContent.append("，另赠");
                    promotionContent.append(giveawayName);
                    promotionContent.append("，赠完即止");
                    //满减内容为空
                    //活动内容为:单笔满¥meetAmount，送礼品giveawayName
                } else {
                    promotionContent.append("满");
                    promotionContent.append(meetAmount);
                    promotionContent.append("元，赠");
                    promotionContent.append(giveawayName);
                    promotionContent.append("，赠完即止");
                }
                //无赠品
                //活动内容为:单笔满¥meetAmount，立减现金¥discountContent
            } else {
                promotionContent.append("满");
                promotionContent.append(meetAmount);
                promotionContent.append("元减");
                promotionContent.append(discountContent);
            }
            //满折活动
            //活动内容为:单笔订单满meetAmount件，立减折扣discountContent%
        } else if (null != discountType && 3 == discountType) {
            promotionContent.append("单笔满");
            promotionContent.append(meetAmount);
            promotionContent.append("件，打");
            promotionContent.append(discountContent);
            promotionContent.append("折");

        }
        r.setPromotionContent(promotionContent.toString());

    }

    @Override
    public ResponseResult queryGuessLikeQuery(WepGuessLikeGoodsParamDTO param) {
        PageUtils page = null;
        try {
            List<GdsListQueryResultVO> likeGoods = null;
            Integer totalCount = null;
            Map<String, Object> stringIntegerMap = this.baseMapper.selectCatIdByGoodsId(param.getGoodsId());
            param.setCatId(((Long) stringIntegerMap.get("catId")).intValue());
            Integer integralGoods = (Integer) stringIntegerMap.get("integralGoods");
            if (null != stringIntegerMap.get("goodsType")) {
                param.setGoodsType(Integer.valueOf(stringIntegerMap.get("goodsType").toString()));
            }
            param.setIntegralGoods(integralGoods);
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            IPage<GdsListQueryResultVO> listQueryResultVOIPage = this.baseMapper.selectLikeGoodsByCatId(new Query<GdsListQueryResultVO>().getPage(data), param);
            page = PageUtils.getPage(listQueryResultVOIPage);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return ResponseResult.success(page);
    }

    @Override
    public ResponseResult queryGdsDetailDesc(Integer commonsId) {
        GdbMerchantGoodsCommonDetailVO detail = goodsCommonDetailMapper.selectByPrimaryKey(commonsId);

        CommonDetailsDescVO gdsCommon = this.baseMapper.selectCommonDetailsDesc(commonsId);
        detail.setBrandName(gdsCommon.getBrandName());


        List<GdbAttributeAssionParamVO> assionParams=goodsCommonAttributeAssociationMapper.selectCommonIds(commonsId);
        for(GdbAttributeAssionParamVO assionParam : assionParams){
            GoodsAttributeVO gdbAttrPram=goodsAttributeMapper.selectAttributeId(assionParam.getAttributeId());
            if(null != gdbAttrPram) {
                assionParam.setAttributeIds(gdbAttrPram.getCommodityAttribute());
            }
            GoodsAttributeVO gdbAttrPram1=goodsAttributeContentMapper.selectAttContentId(assionParam.getAttributeContentId());
            if(null != gdbAttrPram1) {
                assionParam.setAttributeContentIds(gdbAttrPram1.getAttriContent());
            }
        }

        if (null == detail) {
            detail = new GdbMerchantGoodsCommonDetailVO();
        } else {
            String s = detail.getCommonBody();
            Pattern p = Pattern.compile(PATTERN);
            Matcher m = p.matcher(s);
            while (m.find()) {
                detail.setCommonBody(m.group(1));
            }
        }

        detail.setAttributeParam(assionParams);
        return ResponseResult.success(detail);
    }

    @Override
    public ResponseResult queryRecommendGoods(WebIndexRecommendQueryParamDTO param) {
        return ResponseResult.success(this.baseMapper.queryRecommendGoods(param));
    }

    @Override
    public List<GdsBaseDetailResultVO> queryGoodsStartStock(Integer commonId) {
        return this.baseMapper.queryGoodsStartStock(commonId);
    }

    @Override
    public ResponseResult updateGoodsStock(List<WapGoodsSaleSumDTO> wapGood) {
        for (WapGoodsSaleSumDTO wapGoodsSaleSumUpdate : wapGood) {

            GoodsCommonEntity entity = this.baseMapper.selectById(wapGoodsSaleSumUpdate.getCommonId());

            int goodsNum = wapGoodsSaleSumUpdate.getGoodsNum() == null ? 0 : Integer.parseInt(wapGoodsSaleSumUpdate.getGoodsNum());
            this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .eq(GoodsCommonEntity::getCommonId, entity.getCommonId())
                    .set(GoodsCommonEntity::getCommonStock, entity.getCommonStock() + goodsNum));

            GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(wapGoodsSaleSumUpdate.getGoodsId());

            goodsBaseMapper.update(baseEntity, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .eq(GoodsBaseEntity::getGoodsId, baseEntity.getGoodsId())
                    .set(GoodsBaseEntity::getGoodsStock, baseEntity.getGoodsStock() + goodsNum));
            Integer seckillId = goodsBaseMapper.querySeckillInfo(wapGoodsSaleSumUpdate.getGoodsId());
            if(null != seckillId && seckillId > 0){
                Map<String,Object> paramMap = new HashMap<>();
                Integer goodsId = wapGoodsSaleSumUpdate.getGoodsId();
                paramMap.put("seckillId",seckillId);
                paramMap.put("goodsId",goodsId);
                paramMap.put("goodsNum",goodsNum);
                this.baseMapper.updateSaleForSeckill2(paramMap);

            }
            //查询当前商品是否是 供应商待发货商品 如果是即更新商家 也更新供应商
            Map<String,Object> dealerGoods = this.baseMapper.querydealerGoodsFlag(wapGoodsSaleSumUpdate.getGoodsId());
            if(null != dealerGoods){
                //是商家同步供应商的商品 也要修改供应商端的商品客户
                WapGoodsSaleSumUpdateVO supperGoods = this.baseMapper.querySupperGoodsInfo(dealerGoods);
                if(null != supperGoods){
                    supperGoods.setGoodsNum(goodsNum);
                    goodsBaseMapper.updateAddStock(supperGoods);
                    this.baseMapper.updateAddStock(supperGoods);
                }
            }
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateGoodsSalenum(List<WapGoodsSaleSumDTO> wapGood) {
        for (WapGoodsSaleSumDTO wapGoodsSaleSumUpdate : wapGood) {

            GoodsCommonEntity entity = this.baseMapper.selectById(wapGoodsSaleSumUpdate.getCommonId());

            int goodsNum = wapGoodsSaleSumUpdate.getGoodsNum() == null ? 0 : Integer.parseInt(wapGoodsSaleSumUpdate.getGoodsNum());
            this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .eq(GoodsCommonEntity::getCommonId, entity.getCommonId())
                    .set(GoodsCommonEntity::getCommonSalenum, entity.getCommonSalenum() + goodsNum));

            GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(wapGoodsSaleSumUpdate.getGoodsId());

            goodsBaseMapper.update(baseEntity, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .eq(GoodsBaseEntity::getGoodsId, baseEntity.getGoodsId())
                    .set(GoodsBaseEntity::getGoodsSalenum, baseEntity.getGoodsSalenum() + goodsNum));
        }
        return ResponseResult.success();
    }

    @Override
    public List<Integer> selectTransportAreaId(List<Integer> goodsIds) {
        return this.baseMapper.selectTransportAreaId(goodsIds);
    }

    @Override
    public ResponseResult updateGoodsCollect(Map<String, String> paraMap) {
        goodsBaseMapper.updateGoodsCollect(paraMap);
        this.baseMapper.updateGoodsCollect(paraMap);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryIntegralGoodsBygoodsId(Map<String, Object> param) {
        Map<String, Object> map = this.baseMapper.queryIntegralGoodsBygoodsId(param);
        return ResponseResult.success(map);
    }

    @Override
    public Integer queryGoodsIsPlus(Integer commonId) {
        return this.baseMapper.queryGoodsIsPlus(commonId);
    }

    @Override
    public ResponseResult querySupplierGoodsPrice(Map<String, Object> param) {
        Map<String,Object> result =  this.baseMapper.queryBcenterGoodsPrice(param);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryVirtualgoods(Map<String, String> param) {
        Map<String,Object> receiveGoodsDetails = this.baseMapper.queryVirtualgoods(param.get("goodsId"));
        return ResponseResult.success(receiveGoodsDetails);
    }

    @Override
    public ResponseResult updateSaleAndStock(String goodsDetails) {
        List<WapGoodsSaleSumUpdateVO> result = JSON.parseArray(goodsDetails, WapGoodsSaleSumUpdateVO.class);
        for (WapGoodsSaleSumUpdateVO wapGoodsSaleSumUpdate : result) {

            GoodsCommonEntity entity = this.baseMapper.selectById(wapGoodsSaleSumUpdate.getCommonId());

            int num = wapGoodsSaleSumUpdate.getGoodsNum() == null ? 0 : wapGoodsSaleSumUpdate.getGoodsNum();
            int commonStock = Math.max(entity.getCommonStock() - num, 0);
            this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .eq(GoodsCommonEntity::getCommonId, entity.getCommonId())
                    .set(GoodsCommonEntity::getCommonStock, commonStock));

            GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(wapGoodsSaleSumUpdate.getGoodsId());
            int goodsStock = Math.max(baseEntity.getGoodsStock() - num, 0);
            goodsBaseMapper.update(baseEntity, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .eq(GoodsBaseEntity::getGoodsId, baseEntity.getGoodsId())
                    .set(GoodsBaseEntity::getGoodsStock, goodsStock));
            //goodsBaseMapper.updateStock(wapGoodsSaleSumUpdate);
            //this.baseMapper.updateStock(wapGoodsSaleSumUpdate);
            //若为限时秒杀，需要更新秒杀库存
            Integer seckillId = goodsBaseMapper.querySeckillInfo(wapGoodsSaleSumUpdate.getGoodsId());
            if(null != seckillId && seckillId > 0){
                Map<String,Object> paramMap = new HashMap<>();
                Integer goodsId = wapGoodsSaleSumUpdate.getGoodsId();
                Integer goodsNum = wapGoodsSaleSumUpdate.getGoodsNum();
                paramMap.put("seckillId",seckillId);
                paramMap.put("goodsId",goodsId);
                paramMap.put("goodsNum",goodsNum);
                Integer seckillNum = activityServiceClient.querySeckillNum(paramMap);
                if(seckillNum-goodsNum >= 0) {
                    activityServiceClient.updateSaleForSeckill(paramMap);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResponseResult.fail( "秒杀商品库存不足");
                }
            }
            //查询当前商品是否是 供应商待发货商品 如果是即更新商家 也更新供应商
            Map<String,Object> dealerGoods = this.baseMapper.querydealerGoodsFlag(wapGoodsSaleSumUpdate.getGoodsId());
            if(null != dealerGoods){
                //是商家同步供应商的商品 也要修改供应商端的商品客户
                WapGoodsSaleSumUpdateVO supperGoods = this.baseMapper.querySupperGoodsInfo(dealerGoods);
                if(null != supperGoods){
                    supperGoods.setGoodsNum(wapGoodsSaleSumUpdate.getGoodsNum());
                    goodsBaseMapper.updateStock(supperGoods);
                    this.baseMapper.updateStock(supperGoods);
                }
            }
            Map<String,Object> map= new HashMap<>();
            List<Integer> list = new ArrayList<>();
            list.add(wapGoodsSaleSumUpdate.getCommonId());
            map.put("commonIdS",list);
            // 1 是添加  2是删除
            map.put("type",1);
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.submit(() -> {
                // 在这里编写需要异步执行的代码
                // 无论这段代码是否成功，都会在后台进行执行
                // 可以处理耗时操作、异步任务等
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                System.err.println("当前时间：" + dateFormat.format(new Date()));
                MqSendUtils.mqSendGoods(map);
                // 示例：打印当前时间
                System.err.println("当前时间：" + dateFormat.format(new Date()));
            });
            // 关闭线程池
            executorService.shutdown();

        }

        return ResponseResult.success(1, "更新销量", null);
    }
    @Override
    public ResponseResult queryGoodsSpec(GoodsDetailsDTO param) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer commonId = Integer.valueOf(param.getCommonId());
        List<Map> specValues = param.getSpecValues();
        //获取用户信息
        ObjectMapper mapper = new ObjectMapper();
        // 获取user信息
        String userId = null;
        UserInfoVO userinfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.getToken());
        if (null != userinfo) {
            userId = userinfo.getUserId();
        }
        Date sessionTime = param.getSessionTime();


        List<ManageGdsBaseAddResultVO> gdsBases = goodsBaseMapper.selectByCommonId(commonId);
        if(null == gdsBases || gdsBases.isEmpty()) {
            return ResponseResult.fail(0, "没有此商品");
        }
        int goodsId = 0;
        //遍历当前商品的所有规格
        for(ManageGdsBaseAddResultVO record : gdsBases) {
            if(StringUtils.isNotEmpty(record.getSpecValue())) {
                int flag = 0;
                JSONArray array = JSONObject.parseArray(record.getSpecValue());
                List<GoodBaseSpecValuesJsonBeanVO> tempSpecValues = new ArrayList<>();
                //解析当前商品规格 的规格名和规格值
                for(int index = 0;index<array.size();index++ ) {
                    String jsonObject = array.getString(index);
                    GoodBaseSpecValuesJsonBeanVO temp = JSONObject.parseObject(jsonObject, GoodBaseSpecValuesJsonBeanVO.class);
                    tempSpecValues.add(temp);
                }
                //遍历校验用户选中的规格 与 库中查出的哪个 规格名、值匹配，返回对应的规格价格
                for(int i = 0;i<specValues.size();i++) {
                    Map mapSpecValues = specValues.get(i);
                    String recordTempString = JSONObject.toJSONString(mapSpecValues);
                    GoodBaseSpecValuesJsonBeanVO oldSpecValues = JSONObject.parseObject(recordTempString, GoodBaseSpecValuesJsonBeanVO.class);
                    for(GoodBaseSpecValuesJsonBeanVO newSpecValues : tempSpecValues) {
                        if(oldSpecValues.getParamName().trim().equals(newSpecValues.getParamName().trim()) &&
                                oldSpecValues.getParamValue().trim().equals(newSpecValues.getParamValue().trim())) {
                            flag++;
                            continue;
                        }
                    }

                }
                if(specValues.size() == flag) {
                    goodsId = record.getGoodsId();
                }
            }
        }
        GdsBaseDetailResultVO goodsBases = goodsBaseMapper.selectByGoodsId(goodsId);
        goodsBases.setCommodityPrice(goodsBases.getGoodsPrice());

        //查询图片
        List<GdbMerchantGoodsImagesVO> goodsImages = goodsImagesMapper.selectByCommonIdImg(goodsId);
        goodsBases.setGoodsImages(goodsImages);

        // 活动
        ActivityGoodsDetailDTO activityGoodsDetail = dealActivity2(goodsBases.getGoodsId(),goodsBases.getGoodsStock(),
                goodsBases.getGoodsMaxSale(), commonId, goodsBases.getCommonIsXian(), userId, sessionTime);

        if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
            goodsBases.setActivityStatus(activityGoodsDetail.getActivityStatus());
            goodsBases.setActivityGoodsDetailDTO(activityGoodsDetail);
            goodsBases.setCurrentCartQuantity(activityGoodsDetail.getCurrentCartQuantity());
            if (!activityGoodsDetail.getActivityStatus().equals(4)) {
                goodsBases.setActivityPrice(activityGoodsDetail.getActivityPrice());
                goodsBases.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                goodsBases.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());
            }
            //满减赠折活动展示活动内容ZZZ
            if (activityGoodsDetail.getActivityStatus().equals(5)) {
                String promotionContent = "";
                List<ManjianzengzhePromotionContentQueryResultVO> promotionContents = activityServiceClient.selectReductionPolicyPromotionContent(commonId);
                for (ManjianzengzhePromotionContentQueryResultVO r : promotionContents) {
                    Integer discountType = r.getDiscountType();
                    Integer hasGiveaway = r.getHasGiveaway();
                    String discountContent = r.getDiscountContent();
                    boolean mzFlag = discountContent == null || "".equals(discountContent);
                    //满减赠
                    if (discountType == 1) {
                        if (null == goodsBases.getPromotionType() || "".equals(goodsBases.getPromotionType())) {
                            if (hasGiveaway == 1 && mzFlag) {
                                goodsBases.setPromotionType("满赠");
                            } else {
                                goodsBases.setPromotionType("满减");
                            }
                        }
                        //满折
                    } else if (discountType == 3) {
                        goodsBases.setCommonIsXian(6);
                        goodsBases.setActivityStatus(6);
                        goodsBases.setPromotionType("满折扣");
                    }
                    if ("满减".equals(goodsBases.getPromotionType()) && hasGiveaway == 1) {
                        goodsBases.setPromotionType("满减赠");
                    } else if ("满赠".equals(goodsBases.getPromotionType()) && !mzFlag) {
                        goodsBases.setPromotionType("满减赠");
                    }
                    dealPromotionContent(r);

                    promotionContent = promotionContent + r.getPromotionContent() + "\n";

                }
                goodsBases.setPromotionContent(promotionContent);


            }
        }
        if (StringUtils.isNotEmpty(goodsBases.getSpecValue())) {
            List<GoodBaseSpecValuesJsonBeanVO> specValuesJsonBeans = new ArrayList<>();
            JSONArray specValuesJsonBeanArray = com.alibaba.fastjson.JSONObject.parseArray(goodsBases.getSpecValue());
            for(int index = 0;index < specValuesJsonBeanArray.size();index++) {
                com.alibaba.fastjson.JSONObject obj = specValuesJsonBeanArray.getJSONObject(index);
                GoodBaseSpecValuesJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), GoodBaseSpecValuesJsonBeanVO.class);
                specValuesJsonBeans.add(temp);
            }
            goodsBases.setSpecValueList(specValuesJsonBeans);
        }
        return ResponseResult.success(goodsBases);
    }

    @Override
    public ResponseResult queryPackingList(Integer commonId) {
        String packingList = this.baseMapper.selectPackingList(commonId);
        return ResponseResult.success(packingList);
    }

    @Override
    public ResponseResult queryCommonService(Integer commonId) {
        String commonService = this.baseMapper.selectCommonService(commonId);
        return ResponseResult.success(commonService);
    }

    @Override
    public ResponseResult queryIntegralGoodsListFilter(ListPageQueryParamDTO param) {
        // 获取分类id
        GoodsCatSearchChildVO goodsCatSearchChild = null;
        List<WebCatMenuVO> allMenu = null;
        List<Integer> catIds = null;

        if (null != param.getCatId()) {

            // 从缓存中获取
            String cacheCatIds = RedisUtil
                    .get(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + param.getCatId());
            if (null != cacheCatIds && !cacheCatIds.isEmpty()) {
                goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
                catIds = goodsCatSearchChild.getCatIds();
            } else {
                // 查询积分分类
                allMenu = goodsCatMapper.selectAllCat();
                catIds = getMenuList(allMenu, param.getCatId());
                goodsCatSearchChild = new GoodsCatSearchChildVO();
                goodsCatSearchChild.setAllMenu(allMenu);
                goodsCatSearchChild.setCatIds(catIds);
                RedisUtil.set(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + param.getCatId(),
                        JsonUtils.toString(goodsCatSearchChild),RedisUtil.EXRP_MONTH);
            }

            if (!CollectionUtils.isEmpty(catIds)) {
                catIds.add(param.getCatId());
                param.setCatIds(catIds);
                param.setCatId(0);
            }
        }

        // 查询商品列表
        //将对象转换为map
        IPage<GdsListQueryResultVO> page = null;
        try {
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            page = this.baseMapper.selectByWebFilter(new Query<GdsListQueryResultVO>().getPage(data),param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // 添加热搜词
        getHotSearchWords(param);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryShopIndex(ShopIndexDTO param) {
        // 根据shopId查询所有商品
        List<ListQueryResultVO> gdsList = this.baseMapper.selectByShopIndex(param);
        for (ListQueryResultVO gdsListQueryResult : gdsList) {
            gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));

            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(), gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(CommonType.promotionStatus.NOT_PARTICIPATING.getCode())) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if (activityGoodsDetail.getActivityStatus().equals(CommonType.promotionStatus.FULL_REDUCTION_AND_FREE_DISCOUNT.getCode())) {
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(CommonType.promotionStatus.NOT_PARTICIPATING.getCode());
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(CommonType.promotionStatus.NOT_PARTICIPATING.getCode());
            }

        }
        // 查询首页信息
        ResponseResult shopResult = businessServiceClient.shopIndex(param.getShopId());

        if (shopResult.getData() == null) {
            return ResponseResult.fail(BizCodeEnume.NO_STORE_INFORMATION.getMsg());
        }
        ShopIndexVO shopIndex = JSON.parseObject(JSON.toJSONString(shopResult.getData()), ShopIndexVO.class);

        shopIndex.setIsEnshrine(CommonType.commonStatus.YES.getCode());
        Integer shopSumNum = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsCommonEntity>()
                            .eq(GoodsCommonEntity::getShopId, param.getShopId())
                            .eq(GoodsCommonEntity::getShopStatus, CommonType.shopStatus.STORE_OPEN_SUCCESS.getCode())
                            .eq(GoodsCommonEntity::getCommonVerify, CommonType.productReview.PASS.getCode())
                            .eq(GoodsCommonEntity::getCommonState, CommonType.commonSpuState.GOODS_NORMAL.getCode()));


        // 处理轮播信息
        dealShopSlide(shopIndex);


        if (shopIndex.getShopImage() == null || "".equals(shopIndex.getShopImage()) || shopIndex.getShopLogo() == null || "".equals(shopIndex.getShopLogo()) || shopIndex.getWapShopLogo() == null || "".equals(shopIndex.getWapShopLogo())) {
            String configValue = baseServiceClient.selectConfigValueFeign(CommonType.configKey.SHOP_LOGO_WRITING.getDesc());
//            ShopConfigDefaultValueVO shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueVO.class);

            if (shopIndex.getShopImage() == null || "".equals(shopIndex.getShopImage())) {
                shopIndex.setShopImage(configValue);
            }
            if (shopIndex.getShopLogo() == null || "".equals(shopIndex.getShopLogo())) {
                shopIndex.setShopLogo(configValue);
            }
            if ((shopIndex.getWapShopLogo() == null || "".equals(shopIndex.getWapShopLogo())) && shopIndex.getShopLogo() != null) {
                shopIndex.setWapShopLogo(configValue);
            }
            if (shopIndex.getWapShopLogo() == null || "".equals(shopIndex.getWapShopLogo())) {
                shopIndex.setWapShopLogo(configValue);
            }
            if (shopIndex.getShopSlide() == null || "".equals(shopIndex.getShopSlide())) {
                shopIndex.setShopSlide(configValue);
            }
        }
        shopIndex.setShopSumNum(shopSumNum);
        shopIndex.setGdsList(gdsList);
        return ResponseResult.success(shopIndex);
    }

    @Override
    public ResponseResult getDetailByCommonId(Integer commonId) {
       GoodsCommonEntity entity = this.baseMapper.selectById(commonId);
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult updateCommonCollect(String commonId) {
        GoodsCommonEntity commonEntity = this.baseMapper.selectById(commonId);
        if(commonEntity.getCommonCollect()>0){
            this.baseMapper.update(commonEntity, new LambdaUpdateWrapper<GoodsCommonEntity>().eq(GoodsCommonEntity::getCommonId, commonId)
                    .set(GoodsCommonEntity::getCommonId, commonEntity.getCommonCollect() - 1));
        }
      return ResponseResult.success();
    }

    @Override
    public ResponseResult updateStockReduce(WapGoodsSaleSumDTO param) {
        GoodsCommonEntity goodsCommonEntity = this.baseMapper.selectById(param.getCommonId());
        this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                .set(GoodsCommonEntity::getCommonStock, goodsCommonEntity.getCommonStock() + param.getGoodsNum())
                .eq(GoodsCommonEntity::getCommonId, goodsCommonEntity.getCommonId()));

        if (param.getGoodsType().intValue() == 1) {
            UserInfoVO userinfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
            Map<String,Object> map=new HashMap<>();
            map.put("userId",userinfo.getUserId());
            map.put("shopId",param.getTreasureOrderShopId());
            map.put("numberOfGifts",-1);

            userServiceClient.updateTreasureByMap(map);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateCommentCount(Map<String, Object> map) {
       GoodsCommonEntity entity = this.baseMapper.selectById(Integer.valueOf(map.get("commonId").toString()));
        if (null != entity) {
            Integer count = this.baseMapper.update(entity, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .eq(GoodsCommonEntity::getCommonId, entity.getCommonId())
                    .set(GoodsCommonEntity::getCommonEvaluate, entity.getCommonEvaluate() + 1));
            if (count > 0) {
                return ResponseResult.success();
            }
        }

        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR.getCode(), BizCodeEnume.UPDATE_ERROR.getMsg());
    }

    private void dealShopSlide(ShopIndexVO shopBase) {
        // 处理轮播信息
        String[] shopSlideurlArr = null;
        String shopSlide = shopBase.getMobileShopSlide();
        String mobileShopSlideurl = shopBase.getMobileShopSlideurl();

        if (null == shopSlide || "".equals(shopSlide)) {
            shopSlide = shopBase.getShopSlide();
            mobileShopSlideurl = shopBase.getShopSlideurl();
        }
        if (null != shopSlide && !"".equals(shopSlide)) {
            if (mobileShopSlideurl!=null && mobileShopSlideurl.length() > 0) {
                shopSlideurlArr = mobileShopSlideurl.split(",", -1);
            }

            String[] shopSlideArr = shopSlide.split(",", -1);
            List<ShopSlideUrlVO> shopSlideurlList = Lists.newArrayList();
            Integer length = 0;
            if (null != shopSlideurlArr && shopSlideurlArr.length > 0) {
                for (String shopSlideurl : shopSlideurlArr) {
                    ShopSlideUrlVO slideUrlList = new ShopSlideUrlVO();
                    if (!"https:\\".equals(shopSlideurl) && !"http://".equals(shopSlideurl)) {

                        if (shopSlideurl.contains("goodsId") && !shopSlideurl.contains("type=goods")) {
                            String[] gidStrings = shopSlideurl.split("goodsId=");
                            int goodsId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                            CommonAndGoodsVO commonIdAndGoodsId = new CommonAndGoodsVO();
                            GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(goodsId);
                            Integer commonId = baseEntity.getCommonId();
                            commonIdAndGoodsId.setGoodsId(goodsId);
                            commonIdAndGoodsId.setCommonId(commonId);
                            // 跳转商品
                            slideUrlList.setOpType(2);
                            slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                        } else if (shopSlideurl.contains("shopId")) {
                            String[] gidStrings = shopSlideurl.split("shopId=");
                            int shopId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                            // 跳转店铺
                            slideUrlList.setOpType(4);
                            slideUrlList.setShopId(shopId);
                        } else if (shopSlideurl.contains("catId")) {
                            String[] gidStrings = shopSlideurl.split("catId=");
                            int catId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                            // 跳转店铺
                            slideUrlList.setOpType(6);
                            slideUrlList.setCatId(catId);
                        } else if (shopSlideurl.contains("images.oss")) {
                            // 跳转url
                            slideUrlList.setOpType(3);
                            slideUrlList.setUrl(shopSlideurl);
                        } else {
                            String[] gidStrings = shopSlideurl.split("gid=");
                            if (shopSlideurl.contains("gid") && !shopSlideurl.contains("type") && null != gidStrings) {

                                int goodsId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                                CommonAndGoodsVO commonIdAndGoodsId = new CommonAndGoodsVO();
                                GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(goodsId);
                                Integer commonId = baseEntity.getCommonId();
                                commonIdAndGoodsId.setGoodsId(goodsId);
                                commonIdAndGoodsId.setCommonId(commonId);
                                // 跳转商品
                                slideUrlList.setOpType(2);
                                slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                            } else {
                                if (shopSlideurl.contains("gid=") && shopSlideurl.contains("type=goods")) {
                                    String[] amp = shopSlideurl.split("&amp;");
                                    String gid = "";
                                    Integer goodsId = null;
                                    for (String str : amp) {
                                        if (str.contains("gid=")) {
                                            gid = str;
                                        }
                                    }
                                    if (!"".equals(gid)) {
                                        goodsId = Integer.parseInt(gid.split("=")[1]);
                                        CommonAndGoodsVO commonIdAndGoodsId = new CommonAndGoodsVO();
                                        GoodsBaseEntity baseEntity = goodsBaseMapper.selectById(goodsId);
                                        Integer commonId = baseEntity.getCommonId();
                                        commonIdAndGoodsId.setGoodsId(goodsId);
                                        commonIdAndGoodsId.setCommonId(commonId);
                                        // 跳转商品
                                        slideUrlList.setOpType(2);
                                        slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                                    } else {
                                        slideUrlList.setOpType(7);
                                    }

                                } else if (shopSlideurl.contains("type") && !shopSlideurl.contains("gid=")) {
                                    // 跳转活动页
                                    slideUrlList.setOpType(8);
                                    slideUrlList.setActivityPage(shopSlideurl);
                                } else {
                                    slideUrlList.setOpType(7);
                                }

                            }
                        }

                    } else {
                        slideUrlList.setOpType(7);
                    }
                    shopSlideurlList.add(slideUrlList);
                }
                length = shopSlideArr.length;
            } else {
                length = 0;
            }

            List<ShopSlideUrlVO> slideurlList = Lists.newArrayList();
            if (length.equals(shopSlideurlList.size())) {
                for (int i = 0; i < shopSlideurlList.size(); i++) {
                    if (!"".equals(shopSlideArr[i])) {
                        shopSlideurlList.get(i).setShopSlideUrl(shopSlideArr[i]);
                        slideurlList.add(shopSlideurlList.get(i));
                    }
                }
            }

            shopBase.setShopSlideurlList(slideurlList);

        }
    }
    private void getHotSearchWords(ListPageQueryParamDTO param) {
        String commonName = param.getCommonName();
        if (null != commonName && !commonName.equals("")) {
            GdbMerchantSearchWordVO searchWord = this.baseMapper.selectBySearchName(commonName);
            GdbMerchantSearchWordVO record = new GdbMerchantSearchWordVO();
            if (null != searchWord && !searchWord.equals("")) {
                searchWord.setSearchNums(searchWord.getSearchNums() + 1);
                this.baseMapper.updateByPrimaryKeySelective(searchWord);
            } else {
                record.setSearchKeyword(commonName);
                record.setSearchCharIndex(PinyinUtils.ToPinyin(commonName));
                record.setSearchNums(1);
                this.baseMapper.insertSelective(record);
            }
        }
    }
    /**
     * 获取商品分类所有的子分类
     *
     * @param allMenu
     * @param catId
     * @return
     */
    public List<Integer> getMenuList(List<WebCatMenuVO> allMenu, Integer catId) {
        List<Integer> allChildCatIds = Lists.newArrayList();

        if (!CollectionUtils.isEmpty(allMenu)) {
            for (WebCatMenuVO catMenu : allMenu) {
                if (catMenu.getCatId().equals(catId)) {
                    allChildCatIds.add(catId);
                    getChild(allMenu, catMenu.getCatId(), allChildCatIds);
                }

            }
        }
        return allChildCatIds;

    }
    /**
     * 找出子菜单
     *
     * @return
     */
    private List<Integer> getChild(List<WebCatMenuVO> allMenu, Integer parentId, List<Integer> allChildCatIds) {

        List<Integer> childList = Lists.newArrayList();
        for (WebCatMenuVO catMenu : allMenu) {
            if (catMenu.getCatParentId().equals(parentId)) {
                allChildCatIds.add(catMenu.getCatId());
                childList.add(catMenu.getCatId());
                getChild(allMenu, catMenu.getCatId(), allChildCatIds);
            }
        }

        if (CollectionUtils.isEmpty(childList)) {
            return null;
        }

        return allChildCatIds;
    }

    private ActivityGoodsDetailDTO dealActivity(Integer goodsId, Integer commonId, Integer commonIsXian) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣
        if (!commonIsXian.equals(CommonType.promotionStatus.NOT_PARTICIPATING.getCode())) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(CommonType.promotionStatus.SECKILL.getCode())) {
                // 秒杀
                commonIsXian = dealSeckillActivity(goodsId, commonIsXian, activityGoodsDetail);
            } else if (commonIsXian.equals(CommonType.promotionStatus.DISCOUNT.getCode())) {
                // 限时折扣
                commonIsXian = dealDiscountActivity(goodsId, null,commonIsXian, activityGoodsDetail);
            } else if (commonIsXian.equals(CommonType.promotionStatus.COLLAGE.getCode())) {
                // 拼团
                commonIsXian = dealPintuanActivity(commonId, commonIsXian, goodsId, activityGoodsDetail);
            } else if (commonIsXian.equals(CommonType.promotionStatus.FULL_REDUCTION_AND_FREE_DISCOUNT.getCode())) {
                commonIsXian = dealManjianzengzheActivity(commonId, null,commonIsXian, goodsId, activityGoodsDetail);
            }
            activityGoodsDetail.setActivityStatus(commonIsXian);
        }

        return activityGoodsDetail;
    }

    private Integer dealSeckillActivity(Integer goodsId, Integer commonIsXian, ActivityGoodsDetailDTO activityGoodsDetail) {
        Map<String, Object> map = new HashMap<>();
        map.put("goodsId",goodsId);
        AppSeckillGoodsVO seckillGoods = activityServiceClient.selectByGoodsId(map);
        if (null != seckillGoods) {
            if (DateUtils.compareDate2(seckillGoods.getGoodsEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsEndTime());

                activityGoodsDetail.setGoodsBuyCount(seckillGoods.getSeckillNum() != null ? seckillGoods.getSeckillNum() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(seckillGoods.getSeckillPrice());
            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    @Override
    public ResponseResult goodsOrderParam(String goodsId) {
        Map<String,Object> map = this.baseMapper.goodsOrderParam(goodsId);
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult queryByGoodsSalesum(UserTokenBeanDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());
        ManageIndexVO result = new ManageIndexVO();
        if (userPermissionsResult.getFlag()) {
            Integer shopId = Integer.valueOf(userPermissionsResult.getShopId());

            // common_verify商品审核 1通过，0未通过，10审核中
            // common_state商品状态 0下架，1正常，10违规（禁售）
            // 查询审核过的商品
            Integer verify = goodsCommonMapper.selectVerify(shopId);
            // 出售中商品数量
            Integer saleSum = goodsCommonMapper.selectSaleing(shopId);
            // 待审核商品数量
            Integer waitVerify = goodsCommonMapper.selectWaitVerify(shopId);
            // 仓库中的商品
            Integer storeHouse = 0;
            ManageGdsNameQueryDTO param1 = new ManageGdsNameQueryDTO();
            param1.setShopId(shopId.toString());
            //违规商品
            Integer num1 = goodsCommonMapper.selectViolationsGoodsCount(param1);
            //已下架商品
            Integer num2 = goodsCommonMapper.selectStoreGoodsCount(param1);
            //等待审核的商品
            Integer num3 = goodsCommonMapper.selectVerifyGoodsCount(param1);
            //审核失败的商品
            Integer num4 = goodsCommonMapper.selectVerifyFailGoodsCount(param1);
            //待上架经销商品
            Integer num5 = goodsCommonMapper.queryIsPriceUpdateCount(param1);
            storeHouse = num1 + num2 + num3 + num4 + num5;
            // 违规下架商品
            Integer irregularities = goodsCommonMapper.selectIrregularities(shopId);

            result.setIrregularities(irregularities);
            result.setSaleSum(saleSum);
            result.setStoreHouse(storeHouse);
            result.setVerify(verify);
            result.setWaitVerify(waitVerify);

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(result);
    }


    @Override
    public ResponseResult queryByGoodsName(ManageGdsNameQueryDTO param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfoVO != null) {
//            if (userInfoVO.getShopType().equals(CommonType.storeType.SUPPLIER_STORE.getCode())) {
//                param.setSupplyShopId(Integer.valueOf(userInfoVO.getShopId()));
//            }
            if (null == param.getSupplyShopId()) {
                param.setShopId(userInfoVO.getShopId());
            }
            //分页
            //将对象转换为map
            Map data = null;
            try {
                data = ParseMapUtils.beanToMap(param);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            //分页查询数据
            IPage<ManageGdsNameQueryVO> page = this.baseMapper.selectByGdsName(new Query<ManageGdsNameQueryVO>().getPage(data),param);
            List<ManageGdsNameQueryVO> goods = page.getRecords();
            // 查询出售中的商品
            //List<ManageGdsNameQueryVO> goods = goodsCommonMapper.selectByGdsName(param);

            for (ManageGdsNameQueryVO good : goods) {
                List<VoucherMessageVO> voucherMes = goodsCommonMapper.selectVoucherMes(good.getCommonId());
                if (CollectionUtils.isEmpty(voucherMes)) {
                    voucherMes = Lists.newArrayList();
                }
                good.setVoucherMes(voucherMes);
                if(null == good.getSellEdit()){
                    good.setSellEdit(1);
                }

            }
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

    }

    @Override
    @Transactional
    public ResponseResult deleteByCommonId(ManageCommonIdsDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            List<Integer> list = new ArrayList<>();
            List<Integer> commonIds = param.getCommonIds();
            goodsCommonMapper.updateCommonDel(commonIds);
            goodsBaseMapper.updateCommonDel(commonIds);
            goodsCommonDetailMapper.deleteByPrimaryKey(commonIds);
            goodsImagesMapper.deleteByCommonid(commonIds);
            List<Integer> supperCommonids = new ArrayList<>();
            for (Integer SuppercommonId : commonIds) {
                //判断当前是否是是供应商商品 如果是 下架商家对应的商品 并更新es
                List<Integer> dealerCommonIds = goodsCommonMapper.queryIsSupperGoods(SuppercommonId);
                if(null != dealerCommonIds && dealerCommonIds.size() >0 ){
                    //当前商品是供应商商品 所有商家商品下架 更新es
                    goodsCommonMapper.updateOffline(dealerCommonIds);
                    supperCommonids.addAll(dealerCommonIds);
                }
            }
            NoneGoodsUpdateDTO nguParam = new NoneGoodsUpdateDTO();
            nguParam.setCommonIdList(commonIds);
            activityNoneGoodsMapper.deleteNoneGoods(nguParam);
            //通过mq 更新es的商品数据
            Map<String,Object> map= new HashMap<>();
            list.addAll(supperCommonids);
            list.addAll(param.getCommonIds());
            map.put("commonIdS",list);
            // 1 是添加  2是删除
            map.put("type",2);
            MqSendUtils.mqSendGoods(map);

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }


    @Override
    public ResponseResult queryGoodsLockedStatus(GoodsDetailsDTO param) {
        Integer commonIsLock = goodsCommonMapper.selectGoodsLockedStatus(param.getCommonId());
        return ResponseResult.success(commonIsLock);
    }

    @Override
    public ResponseResult selectplusgoods() {
        List<PcConfigGoodsVO> pcConfigGoodsParams = this.baseMapper.pcConfigGoods();
        return ResponseResult.success(pcConfigGoodsParams);
    }


    @Override
    public ResponseResult queryStoreHouse(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        ManageGoodsListQueryVO goodsList = new ManageGoodsListQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectStoreGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);

            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

    }


    @Override
    public ResponseResult queryVerifyGoods(ManageGdsNameQueryDTO param) throws IllegalAccessException {

        ManageGoodsListQueryVO goodsList = new ManageGoodsListQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectVerifyGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }


    }


    @Override
    public ResponseResult queryVerifyFailGoods(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        ManageGoodsListQueryVO goodsList = new ManageGoodsListQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectVerifyFailGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);


            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

    }


    @Override
    public ResponseResult queryViolationsGoods(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        ManageGoodsListQueryVO goodsList = new ManageGoodsListQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            Date commonSellTime = new Date();
            param.setCommonSellTime(commonSellTime);
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectViolationsGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }


    }


    @Override
    public ResponseResult queryGoodsByTemplateId(TransportTemplateDetailDeleteDTO param) throws IllegalAccessException {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());
        param.setShopId(userPermissionsResult.getShopId());
        ManageTransportVO result = new ManageTransportVO();

        Map data= ParseMapUtils.beanToMap(param);
        IPage<ManageTransportGoodsVO> page=this.baseMapper.selectByTemplateId(new Query<ManageTransportGoodsVO>().getPage(data),
                param);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryGoodsByTransportAreaId(TransportTemplateDetailDeleteDTO param) throws IllegalAccessException {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());
        param.setShopId(userPermissionsResult.getShopId());
        ManageTransportVO result = new ManageTransportVO();

        Map data= ParseMapUtils.beanToMap(param);
        IPage<ManageTransportGoodsVO> page=this.baseMapper.selectByTransportAreaId(new Query<ManageTransportGoodsVO>().getPage(data),
                param);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public void updateCommonIsXian2(List<Integer> commonIdList) {
        goodsCommonMapper.updateCommonIsXian2(commonIdList);
    }

    @Override
    public void updateCommonIsXian(Map<String, Object> param) {
        Integer commonIsXian = (Integer) param.get("commonIsXian");
        Integer commonId = (Integer) param.get("commonId");
        goodsCommonMapper.updateCommonIsXian(commonIsXian,commonId);
    }

    @Override
    public ResponseResult queryGoodsList(GoodsListQueryDTO param) {

        PromotionGoodsVO result = new PromotionGoodsVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            param.setPage((param.getPage() - 1) * param.getLimit());

            List<PromotionGoodsListVO> goodsList = goodsCommonMapper.selectPromotionGoodsList(param);
            Integer totalCount = goodsCommonMapper.selectPromotionGoodsListCount(param);
            totalCount = totalCount==null?0:totalCount;
            result.setGoodsList(goodsList);
            result.setTotalCount(totalCount);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryactivityGoods(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        ManageGoodsListQueryVO goodsList = new ManageGoodsListQueryVO();

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());
        if (userPermissionsResult.getFlag()) {
            if (null == param.getSupplyShopId()) {
                param.setShopId(userPermissionsResult.getShopId());
            }
            // 查询出售中的商品
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectactivityGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);

            for (ManageGdsNameQueryVO good : page.getRecords()) {
                List<VoucherMessageVO> voucherMes = goodsCommonMapper.selectVoucherMes(good.getCommonId());
                if (CollectionUtils.isEmpty(voucherMes)) {
                    voucherMes = Lists.newArrayList();
                }
                good.setVoucherMes(voucherMes);
                if(null == good.getSellEdit()){
                    good.setSellEdit(1);
                }
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

    }



    @Override
    public ResponseResult queryManageSpaceAllGoods(PlatFormAllGoodsQueryDTO param) {
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<PlatFormAllGoodsVO> iPage = goodsCommonMapper.selectByAllGoodsToSpace(new Query<PlatFormAllGoodsVO>().getPage(map), param);
        List<PlatFormAllGoodsVO> records = iPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (PlatFormAllGoodsVO good : records) {
                List<String> noneNameList = goodsCommonMapper.selectNoneName(Integer.valueOf(good.getGoodsId()));
                good.setNoneNameList(noneNameList);
            }
        }
        return ResponseResult.success(PageUtils.getPage(iPage));
    }

    @Override
    public ResponseResult goodsCount(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                // 类型:1、全部，2、当日，3、本周，4、本月，5、年度
                Integer type = (Integer) map.get("type");
                Integer goodsCount = 0;
                if (type == 1) {
                    goodsCount = this.baseMapper.queryAllGoodsCount();
                } else if (type == 2) {
                    goodsCount = this.baseMapper.queryTodayGoodsCount();
                } else if (type == 3) {
                    goodsCount = this.baseMapper.queryWeekGoodsCount();
                } else if (type == 4) {
                    goodsCount = this.baseMapper.queryMonthGoodsCount();
                } else {
                    goodsCount = this.baseMapper.queryYearGoodsCount();
                }
                return ResponseResult.success(goodsCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult goodsTodayNumber(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer goodsCount = this.baseMapper.queryTodayGoodsCount();
                return ResponseResult.success(goodsCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult queryAllGoods(PlatFormAllGoodsDTO param) throws IllegalAccessException {

        //查询所有商品
        Map data= ParseMapUtils.beanToMap(param);
        IPage<PlatFormAllGoodsVO> page=this.baseMapper.selectByAllGoods(new Query<PlatFormAllGoodsVO>().getPage(data),
                param);
        for (PlatFormAllGoodsVO good : page.getRecords()) {
            //查询当前商品所上上架的专区
            List<String> noneNameList = goodsCommonMapper.selectNoneName(good.getCommonId());
            good.setNoneNameList(noneNameList);

            List<GoodsStockVO> stockEntityList = new ArrayList<>();
            //查询当前商品不同规格下的库存
            stockEntityList = goodsCommonMapper.selectStocks(good.getCommonId());
            good.setGoodsStockEntityList(stockEntityList);

            List<HotGoodsDTO> hotGoodsDTOList = this.baseMapper.queryHotGoods(good.getCommonId());
            for(HotGoodsDTO hotGoodsDTO : hotGoodsDTOList){
                if(hotGoodsDTO.getGoodsState().intValue() == 1){
                    good.setHotState(1);
                    break;
                }else{
                    good.setHotState(2);
                }
            }
            // 1 是代发商品
            if(1 == good.getDealerGoodsFlag() ){
                // 查询代发商品 所同步的供应商商品是否在售
                Integer supplierGoodsStart = goodsCommonMapper.querySupplierGoodsStart(good.getCommonId());
                if(0 < supplierGoodsStart){
                    // 商品 不在售 所有经销商品不能 上架
                    good.setGoodsDealerDesc("商品在供应商端未在售,经销商品不能上架!");
                }
            }
        }


        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryDealerGoods(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ManageGdsNameQueryVO> page=this.baseMapper.queryDealerGoods(new Query<ManageGdsNameQueryVO>().getPage(data),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult batchUpdateCorner(Map<String, Object> map) {
        Integer cornerId=Integer.valueOf(map.get("cornerId").toString());
        List<Integer> commonIdList= (List<Integer>) map.get("commonIdList");
        this.baseMapper.update(null,new LambdaQueryWrapper<GoodsCommonEntity>()
                       .eq(GoodsCommonEntity::getCornerId,cornerId)
                       .in(GoodsCommonEntity::getCommonId,commonIdList));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult deleteCornerMarker(Map<String, Object> map) {
        Integer cornerId=Integer.valueOf(map.get("cornerId").toString());
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsCommonEntity>()
                                       .eq(GoodsCommonEntity::getCornerId,cornerId));
        if (null != count && count != 0) {
            return ResponseResult.fail(BizCodeEnume.DISASSOCIATE_PRODUCT);
        }
        this.baseMapper.deleteCornerMarker(Integer.valueOf(map.get("cornerId").toString()));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateIntegralGoods(IntegralCommonDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            Integer shopId = 0;
            // 查询店铺名称
            param.setShopName("平台店铺");
            param.setShopId(shopId.toString());
            param.setCommonCubage(new BigDecimal(0));
            Integer commonId = param.getCommonId();

            if (param.getCommonState() == null || param.getCommonState() == 0) {
                param.setCommonState(0);
            }
            // 判断主图类型
            if (StringUtils.isNotEmpty(param.getCommonVideo())) {
                param.setType(2);
            }
            // 获取公共信息表规格值和goodsid
            List<BaseAddParamDTO> gdsBases = param.getGdsBases();
            List<BaseAddParamDTO> addGoodsBases = Lists.newArrayList();
            List<BaseAddParamDTO> updateGoodsBases = Lists.newArrayList();
            List<Integer> updateGoodsStatus = Lists.newArrayList();
            String image = null;
            if (!CollectionUtils.isEmpty(param.getGoodsImages())) {
                image = param.getGoodsImages().get(0).getImagesImage();
                param.setCommonImage(image);
            }
            if (!CollectionUtils.isEmpty(gdsBases)) {
                for (BaseAddParamDTO gdsBase : gdsBases) {
                    gdsBase.setGoodsPromotionTips(param.getCommonPromotionTips());
                    if (null == param.getBrandId()) {
                        gdsBase.setBrandId(0);
                    }
                    if (param.getCommonState().equals(1)) {
                        gdsBase.setGoodsIsShelves(1);
                    } else {
                        gdsBase.setGoodsIsShelves(2);
                    }
                    gdsBase.setGoodsName(param.getCommonName());
                    gdsBase.setGoodsImage(image);
                    gdsBase.setGoodsIsRecommend(param.getCommonIsRecommend());
                    gdsBase.setCommonId(commonId);
                    gdsBase.setShopId(shopId.toString());
                    List<GoodBaseSpecValuesVO> specValues = gdsBase.getSpecValues();
                    String goodsSpec = null;
                    for (GoodBaseSpecValuesVO specValue : specValues) {
                        if (goodsSpec == null) {
                            goodsSpec = specValue.getParamValue();
                            continue;
                        }
                        goodsSpec = goodsSpec + "+" + specValue.getParamValue();
                    }
                    gdsBase.setGoodsSpec(goodsSpec);
                    if (null == gdsBase.getGoodsId()) {
                        addGoodsBases.add(gdsBase);
                    } else {
                        updateGoodsStatus.add(gdsBase.getGoodsId());
                        updateGoodsBases.add(gdsBase);
                    }
                }
            } else {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
            }
            param.setCommonUpdateBy(Integer.parseInt(userInfo.getUserId()));
            param.setCommonUpdateTime(new Date());

            // 修改状态为审核中
            param.setCommonVerify(1);
            param.setSpecParamJson(JSONObject.toJSONString(param.getSpecParam()));
            // 插入数据到公共信息表,并获取common_id
            this.baseMapper.updateGdsCommon(param);
            // 更新商品状态
            this.baseMapper.updateGoodsIsShelves(updateGoodsStatus, commonId);

            // 添加goods_base
            if (!CollectionUtils.isEmpty(addGoodsBases)) {
                for (BaseAddParamDTO addGoodsBase : addGoodsBases) {
                    this.baseMapper.updateGdsBasesBatch2Obj(addGoodsBase);
                }
            }
            if (!CollectionUtils.isEmpty(updateGoodsBases)) {
                for (BaseAddParamDTO record : updateGoodsBases) {
                    if (null == record.getGoodsMaxSale() || 0 == record.getGoodsMaxSale()) {
                        record.setGoodsMaxSale(record.getGoodsStock());
                    }
                    this.baseMapper.updateGdsBasesBatch2Obj(record);
                }
            }
            // 添加商品详情
            GoodsCommonDetailDTO goodsCommonDetail = param.getGoodsCommonDetail();
            if (null != goodsCommonDetail) {

               GoodsCommonDetailDTO selectByPrimaryKey = this.baseMapper.selectCommonDetailByPrimaryKey(commonId);
                goodsCommonDetail.setCommonId(commonId);
                if (null != selectByPrimaryKey) {
                    this.baseMapper.updateByPrimaryKey(goodsCommonDetail);
                } else {
                    this.baseMapper.insertSelective2(goodsCommonDetail);
                }

            }
            // 添加商品属性表
            String commonProperty = param.getCommonProperty();
            if (null != commonProperty && !"".equals(commonProperty)) {
                List<GoodsPropertyDTO> propertys = JSON.parseArray(commonProperty, GoodsPropertyDTO.class);
                if (propertys.size() > 0) {
                    for (GoodsPropertyDTO property : propertys) {
                        property.setCommonId(commonId);
                    }
                    this.baseMapper.insertBatch(propertys);
                }
            }
            // 添加商品图片
            List<GoodsImagesDTO> goodsImages = param.getGoodsImages();
            List<GoodsImagesDTO> addImages = new ArrayList<GoodsImagesDTO>();
            List<GoodsImagesDTO> updateImages = new ArrayList<GoodsImagesDTO>();
            List<Integer> removeGoodsImage = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(goodsImages)) {
                for (GoodsImagesDTO goodsImage : goodsImages) {
                    goodsImage.setCommonId(param.getCommonId());
                    goodsImage.setGoodsId(gdsBases.get(0).getGoodsId());
                    goodsImage.setShopId(shopId.toString());
                    if (null == goodsImage.getImagesId() || "".equals(goodsImage.getImagesId().toString())) {
                        addImages.add(goodsImage);
                    } else {
                        removeGoodsImage.add(goodsImage.getImagesId());
                        updateImages.add(goodsImage);
                    }
                }
                if (!CollectionUtils.isEmpty(removeGoodsImage)) {
                    this.baseMapper.deleteByGoodsImageIds(removeGoodsImage, commonId);
                }
                if (updateImages.size() > 0) {
                    this.baseMapper.updateBatch(goodsImages);
                } else {
                    this.baseMapper.deleteByCommonId2(commonId);
                }
                if (addImages.size() > 0) {
                    this.baseMapper.insertGoodsImage(addImages);
                }
            }
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult goodsQueryDetail(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            ManageIntegraCommonVO commonResult = new ManageIntegraCommonVO();
            Integer commonId = Integer.valueOf(map.get("commonId").toString());
            Integer shopId = 0;

            // 返回结果
            GoodsCommonEntity common = this.baseMapper.selectOne(new LambdaQueryWrapper<GoodsCommonEntity>()
                                        .eq(GoodsCommonEntity::getShopStatus,CommonType.shopStatus.STORE_OPEN_SUCCESS.getCode())
                                        .eq(GoodsCommonEntity::getCommonId,map.get("commonId").toString()));

            if (StringUtils.isNotEmpty(common.getSpecParam())) {
                List<SpecParamJsonBeanDTO> list = new ArrayList<>();
                JSONArray jsonSpecParam = JSONObject.parseArray(common.getSpecParam());
                for (int index = 0; index < jsonSpecParam.size(); index++) {
                    JSONObject obj = jsonSpecParam.getJSONObject(index);
                    SpecParamJsonBeanDTO temp = JSONObject.parseObject(obj.toJSONString(), SpecParamJsonBeanDTO.class);
                    list.add(temp);
                }
                common.setSpecParamList(list);
            }


            // 设置运费和售卖区域
            ManageTransportTemplateVO transportTemplate = this.baseMapper.selectTransportTemplateById(common.getTransportTemplate());

            ManageTransportAreaVO transportAreas = this.baseMapper.selectTransportAreaByIdArea(common.getTransportAreaId());
            common.setTransportTemplates(transportTemplate);
            common.setTransportAreas(transportAreas);
            // 规格跟着商品走
            if (StringUtils.isEmpty(common.getSpecParam())) {
                // 查询规格名称
                List<ManageSpecNameVO> goodsSpec = this.baseMapper.selectSpecByTypeId(common.getTypeId());
                common.setCommonSpecNameList(goodsSpec);
                // 查询规格值
                ManageSpecValueInfoDTO specValueQuery = new ManageSpecValueInfoDTO();
                specValueQuery.setShopId(shopId.toString());
                specValueQuery.setCatId(common.getCatId().toString());
                specValueQuery.setTypeId(common.getTypeId());
                List<ManageSpecValueInfoDTO> specValueList = this.baseMapper.selectSpecByShopId(specValueQuery);
                List<ManageSpecValueResultEditDTO> manageSpecValueResultEditsList = new ArrayList<>();
                for (ManageSpecValueInfoDTO manageSpecValueResult : specValueList) {
                    ManageSpecValueResultEditDTO manageSpecValueResultEdit = new ManageSpecValueResultEditDTO();
                    specValueQuery.setSpecId(manageSpecValueResult.getSpecId());
                    List<ManageSpecValueResultSolDTO> stringList = this.baseMapper.selectSpecByShopId3(specValueQuery);
                    manageSpecValueResultEdit.setCatId(manageSpecValueResult.getCatId());
                    manageSpecValueResultEdit.setSpecId(manageSpecValueResult.getSpecId());
                    manageSpecValueResultEdit.setSpecName(manageSpecValueResult.getSpecName());
                    manageSpecValueResultEdit.setSpecValueId(manageSpecValueResult.getSpecValueId());
                    manageSpecValueResultEdit.setSpecValueNames(stringList);
                    manageSpecValueResultEditsList.add(manageSpecValueResultEdit);
                }

                common.setCommonSpecValueList(manageSpecValueResultEditsList);
            }
            // 处理店铺自定义分类
            List<ManageGdsBaseInfoDTO> gdsBases = this.baseMapper.selectByCommonId3(commonId);

            GoodsCommonDetailDTO goodsCommonDetail = this.baseMapper.selectCommonDetailByPrimaryKey(commonId);

            // 商品图片
            List<GoodsImagesDTO> goodsImages = this.baseMapper.selectByCommonId4(commonId, shopId);
            commonResult.setCommonResult(common);
            commonResult.setGdsBases(gdsBases);
            commonResult.setGoodsCommonDetail(goodsCommonDetail);
            if (CollectionUtils.isEmpty(goodsImages)) {
                GoodsImagesDTO goodsImage = new GoodsImagesDTO();
                goodsImage.setImagesImage(common.getCommonImage());
                goodsImage.setImagesDisplayorder(0);
                goodsImage.setShopId(shopId.toString());
                goodsImage.setImagesIsDefault(1);
                goodsImages.add(goodsImage);
            }
            commonResult.setGoodsImages(goodsImages);
            return ResponseResult.success(commonResult);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult addIntegralGoods(ManageGdsCommonPublishDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            UserPermissionsVO userPermissionsResult = new UserPermissionsVO();
            userPermissionsResult.setShopId(0);
            userPermissionsResult.setUserId("");
            Integer commonId = null;
            Integer shopId = userPermissionsResult.getShopId();
            param.setShopId(shopId.toString());
            param.setCommonUpdateBy(userInfo.getUserId());
            param.setCommonUpdateTime(new Date());
            // 初始化默认值
            //上架
            param.setCommonState(1);
            //商品重量
            param.setCommonCubage(new BigDecimal(0));
            param.setGoodsId("0");
            //审核通过
            param.setCommonVerify(1);
            //库存
            param.setCommonStock(0);
            param.setCommonAddTime(new Date());
            param.setCommonSellTime(new Date());
            //积分商品 0是 1否
            param.setIntegralGoods(0);
            //0代表不限购
            short commonLimit = 0;
            param.setCommonLimit(commonLimit);
            String image = null;
            if (!CollectionUtils.isEmpty(param.getGoodsImages())) {
                image = param.getGoodsImages().get(0).getImagesImage();
                param.setCommonImage(image);
            }
            // 获取店铺区域id
            param.setDistrictId(0);
            param.setShopName("平台店铺");
            //不是自营商品
            param.setShopSelfSupport(0);
            // 判断主图类型
            if (StringUtils.isNotEmpty(param.getCommonVideo())) {
                param.setType(2);
            }
            //商铺状态 开店成功
            param.setShopStatus(3);
            param.setCommonSpecValue("");
            // 将规格 和 规格值保存到数据库 规格跟着商品走
            param.setSpecParamJson(JSON.toJSONString(param.getSpecParam()));
            // 添加数据到公共信息表,并获取common_id
            this.baseMapper.newInsertGdsCommonObj(param);

            commonId = param.getCommonId();
            // 获取goods_base,赋值commomid
            Integer goodsId = null;
            List<ManageGdsBaseAddPublishDTO> gdsBases = param.getGdsBases();
            for (ManageGdsBaseAddPublishDTO gdsBase : gdsBases) {
                gdsBase.setGoodsPromotionTips(param.getCommonPromotionTips());
                gdsBase.setCommonId(commonId);
                gdsBase.setShopId(0+"");
                gdsBase.setShopName("平台店铺");
                gdsBase.setGoodsIsRecommend(param.getCommonIsRecommend());
                gdsBase.setGoodsImage(image);
                if (gdsBase.getBrandId() == null) {
                    gdsBase.setBrandId(0);
                }
                if (gdsBase.getGoodsAlarm() == null) {
                    gdsBase.setGoodsAlarm(0);
                }
                if (gdsBase.getGoodsMaxSale() == null) {
                    gdsBase.setGoodsMaxSale(0);
                }

                BaseAddParamDTO manageGdsBaseAddParam = new BaseAddParamDTO();
                manageGdsBaseAddParam.setSpecId(gdsBase.getSpecId());
                manageGdsBaseAddParam.setTypeId(gdsBase.getTypeId());
                if (StringUtils.isNotBlank(gdsBase.getGoodsSpec())) {
                    manageGdsBaseAddParam.setGoodsName("平台店铺" + "(" + gdsBase.getGoodsSpec() + ")");
                } else {
                    manageGdsBaseAddParam.setGoodsName(gdsBase.getGoodsName());
                }
                //带查询
                manageGdsBaseAddParam.setGoodsId(gdsBase.getGoodsId());
                manageGdsBaseAddParam.setCommonId(gdsBase.getCommonId());
                manageGdsBaseAddParam.setShopId(0+"");
                manageGdsBaseAddParam.setShopName("平台店铺");
                manageGdsBaseAddParam.setGoodsPromotionTips(gdsBase.getGoodsPromotionTips());
                manageGdsBaseAddParam.setCatId(gdsBase.getCatId());
                manageGdsBaseAddParam.setGoodsSpecValue(gdsBase.getGoodsSpecValue());
                manageGdsBaseAddParam.setGoodsPrice(gdsBase.getGoodsPrice());
                manageGdsBaseAddParam.setGoodsMarketPrice(gdsBase.getGoodsMarketPrice());
                manageGdsBaseAddParam.setGoodsStock(gdsBase.getGoodsStock());
                manageGdsBaseAddParam.setGoodsAlarm(gdsBase.getGoodsAlarm());
                manageGdsBaseAddParam.setGoodsCode(gdsBase.getGoodsCode());
                manageGdsBaseAddParam.setGoodsBarcode(gdsBase.getGoodsBarcode());
                manageGdsBaseAddParam.setGoodsIsRecommend(gdsBase.getGoodsIsRecommend());
                manageGdsBaseAddParam.setGoodsImage(gdsBase.getGoodsImage());
                //商品上架
                manageGdsBaseAddParam.setGoodsIsShelves(1);
                manageGdsBaseAddParam.setBrandId(gdsBase.getBrandId());
                manageGdsBaseAddParam.setGoodsCubage(gdsBase.getGoodsCubage());
                manageGdsBaseAddParam.setGoodsBabyPrice(gdsBase.getGoodsBabyPrice());
                manageGdsBaseAddParam.setGoodsMinSale(gdsBase.getGoodsMinSale());
                //规格跟着商品走
                manageGdsBaseAddParam.setIsUse(gdsBase.getIsUse());
                // 商家编号
                manageGdsBaseAddParam.setMerchantCode(gdsBase.getMerchantCode());
                // 商品编码
                manageGdsBaseAddParam.setCommodityBarTypeCode(gdsBase.getCommodityBarTypeCode());
                // 规格
                manageGdsBaseAddParam.setSpecValue(JSON.toJSONString(gdsBase.getSpecValues()));
                //积分商品所需的积分
                manageGdsBaseAddParam.setNeedIntegral(gdsBase.getNeedIntegral());
                List<GoodBaseSpecValuesJsonBeanDTO> specValues = gdsBase.getSpecValues();
                String goodsSpec = null;
                for (GoodBaseSpecValuesJsonBeanDTO specValue : specValues) {
                    if (goodsSpec == null) {
                        goodsSpec = specValue.getParamValue();
                        continue;
                    }
                    goodsSpec = goodsSpec + "+" + specValue.getParamValue();
                }
                manageGdsBaseAddParam.setGoodsSpec(goodsSpec);
                // 体积
                if (StringUtils.isNotEmpty(gdsBase.getGoodsVolume())) {
                    BigDecimal goodsVolume = new BigDecimal(gdsBase.getGoodsVolume());
                    manageGdsBaseAddParam.setGoodsVolume(goodsVolume);
                }
                // 商品成本价
                if (null != param.getCommonCostPrice()) {
                    manageGdsBaseAddParam.setGoodsCostPrice(param.getCommonCostPrice());
                }
                // 直播卖点
                if (StringUtils.isNotEmpty(param.getSellingPoint())) {
                    manageGdsBaseAddParam.setSellingPoint(param.getSellingPoint());
                }
                // 是否寄样
                if (null != gdsBase.getGoodsSendBack()) {
                    manageGdsBaseAddParam.setGoodsSendBack(gdsBase.getGoodsSendBack());
                }
                //限购不设置 则默认最多购买数量是商品的库存
                manageGdsBaseAddParam.setGoodsMaxSale(gdsBase.getGoodsMaxSale());
                if (null == gdsBase.getGoodsMaxSale() || 0 == gdsBase.getGoodsMaxSale()) {
                    manageGdsBaseAddParam.setGoodsMaxSale(gdsBase.getGoodsStock());
                }
                if (null != gdsBase.getCommission()) {
                    manageGdsBaseAddParam.setCommission(gdsBase.getCommission());
                }
                this.baseMapper.insertGdsBasesObj(manageGdsBaseAddParam);
                goodsId = this.baseMapper.getByGoodsId();
                gdsBase.setGoodsId(goodsId != null && goodsId != 0 ? goodsId : manageGdsBaseAddParam.getGoodsId());
            }
            // 添加商品属性表
            String commonProperty = param.getCommonProperty();
            if (!StringUtils.isEmpty(commonProperty)) {
                List<GoodsPropertyDTO> propertys = JSON.parseArray(commonProperty, GoodsPropertyDTO.class);
                if (propertys.size() > 0) {
                    for (GoodsPropertyDTO property : propertys) {
                        property.setCommonId(commonId);
                    }
                    this.baseMapper.insertBatch(propertys);
                }

            }
            // 添加商品详情
            GdbMerchantGoodsCommonDetailDTO goodsCommonDetail = param.getGoodsCommonDetail();
            if (null != goodsCommonDetail) {
                goodsCommonDetail.setCommonId(commonId);
                this.baseMapper.insertSelective3(goodsCommonDetail);
            }
            // 添加商品图片
            List<GdbMerchantGuiGeGoodsImagesDTO> goodsImages = param.getGoodsImages();
            if (!CollectionUtils.isEmpty(goodsImages)) {
                for (GdbMerchantGuiGeGoodsImagesDTO goodsImage : goodsImages) {

                    if (goodsImage.getImagesDisplayorder() == null) {
                        goodsImage.setImagesDisplayorder(0);
                    }
                    if (goodsImage.getImagesIsDefault() == null) {
                        goodsImage.setImagesIsDefault(1);
                    }
                    goodsImage.setShopId(shopId);
                    goodsImage.setCommonId(commonId);
                    goodsImage.setGoodsId(goodsId);
                }

            } else {
                GdbMerchantGuiGeGoodsImagesDTO goodsImage = new GdbMerchantGuiGeGoodsImagesDTO();
                if (goodsImage.getImagesDisplayorder() == null) {
                    goodsImage.setImagesDisplayorder(0);
                }
                if (goodsImage.getImagesIsDefault() == null) {
                    goodsImage.setImagesIsDefault(1);
                }
                goodsImage.setShopId(shopId);
                goodsImage.setCommonId(commonId);
                goodsImage.setGoodsId(goodsId);
                goodsImages.add(goodsImage);
            }
            if (!goodsImages.isEmpty()) {
                for (GdbMerchantGuiGeGoodsImagesDTO recordImage : goodsImages) {
                    this.baseMapper.insertGoodsImages(recordImage);
                }
            }
            //多规格需求 2020/10/15
            // 更新商品规格
            //String commonSpecName = param.getCommonSpecName();
            //String[] result = commonSpecName.split(",");
            //for (String specNameVar : result) {
                //System.out.println(specNameVar);
                // 更新商品规格
                newUpdateCommonSpec(commonId, gdsBases);

            //}

            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
    }

    @Override
    public ResponseResult queryVerifyNum(Map<String, Object> map) {
        //蜂巢审核数
        Integer honeycombNum = this.baseMapper.selectNoVerify();
        //查询审核中商品
        Integer goodsNum = this.baseMapper.selectByGoodsCount();
        //查询审核中店铺
        Integer shopNum = this.baseMapper.selectByShopCount();
        map.put("honeycombNum",honeycombNum);
        map.put("goodsNum",goodsNum);
        map.put("shopNum",shopNum);
        return ResponseResult.success(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateGoodsCommonByMap(Map<String, Object> map) {
        Integer count = this.baseMapper.updateGoodsCommonByMap(map);
        if (count > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public List<Integer> queryCommonIdByShopId(Integer shopId) {
            List<Integer> commonIds = this.baseMapper.queryCommonIdByShopId(shopId);
            return commonIds;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateCommonState(CommonShopStateDTO commonParam) {
        Integer count = this.baseMapper.updateCommonState(commonParam);
        if (count > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    private void newUpdateCommonSpec(Integer commonId, List<ManageGdsBaseAddPublishDTO> addGoodsBases) {
        List<CommonSpecValueVO> commonSpecValues = Lists.newArrayList();
        Integer commonStock = 0;
        // 更新goods_common中规格
        UpdateGdsSpecParamDTO updateGdsSpecParam = new UpdateGdsSpecParamDTO();

        for (ManageGdsBaseAddPublishDTO goodsBase : addGoodsBases) {
            BaseAddParamDTO manageGdsBaseAddParam = new BaseAddParamDTO();
            manageGdsBaseAddParam.setGoodsSpec(goodsBase.getGoodsName());
            manageGdsBaseAddParam.setSpecId(goodsBase.getSpecId());
            manageGdsBaseAddParam.setTypeId(goodsBase.getTypeId());

            CommonSpecValueVO value = new CommonSpecValueVO();
            value.setCommonId(commonId);
            value.setGoodsId(goodsBase.getGoodsId());
            commonStock = commonStock + goodsBase.getGoodsStock();
            commonSpecValues.add(value);
        }
        ManageGdsBaseAddPublishDTO manageGdsBase = addGoodsBases.get(0);
        updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));
        updateGdsSpecParam.setCommonStock(commonStock);
        //查询goodsId
        updateGdsSpecParam.setGoodsId(manageGdsBase.getGoodsId().toString());
        updateGdsSpecParam.setCommonPrice(manageGdsBase.getGoodsPrice());
        updateGdsSpecParam.setCommonMarketPrice(manageGdsBase.getGoodsMarketPrice());
        updateGdsSpecParam.setCommonImage(manageGdsBase.getGoodsImage());
        updateGdsSpecParam.setCommonAlarm(manageGdsBase.getGoodsAlarm());
        updateGdsSpecParam.setCommonCubage(manageGdsBase.getGoodsCubage());
        updateGdsSpecParam.setCommonId(commonId);
        updateGdsSpecParam.setCommonBabyPrice(manageGdsBase.getGoodsBabyPrice());
        updateGdsSpecParam.setTypeId(manageGdsBase.getTypeId());

        this.baseMapper.updateGdsSpec(updateGdsSpecParam);
    }


    @Override
    public ResponseResult queryByMonth(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            List<ShopGroupingStatisticsVO> goodsGroupingList =  new ArrayList<>();
            String year = DateUtils.getYear();//获取年
            //循环遍历每月开始时间和结束时间
            for (int i = 1; i <= 12 ; i++) {
                ShopGroupingStatisticsVO shopGroupingStatistics = new ShopGroupingStatisticsVO();
                //获取当前年 的某月 的开始 结束时间
                Map<String, String> stringStringMap = DateUtils.scheduleTimeNday(Integer.valueOf(year), i);
                Integer num = this.baseMapper.queryGoodsGrouping2(stringStringMap);
                shopGroupingStatistics.setNum(num);
                shopGroupingStatistics.setTime(DateUtils.dateGeShiHua(stringStringMap.get("startTimeStr"),"yyyy年MM月"));
                goodsGroupingList.add(shopGroupingStatistics);
            }
            return ResponseResult.success(goodsGroupingList);
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult putAway(DealerGoodsUserInfoDTO goodsUserInfo) {
        ResponseResult resultResp;
        try {
            if(!CollectionUtils.isEmpty(goodsUserInfo.getCommonIdList())){
                return this.goodsPutawayBatch(goodsUserInfo);
            }

            ManageGdsCommonResultVO supplyGoodsCommon = goodsCommonMapper.selectPutawayGoodsInfo(goodsUserInfo.getCommonId());
            // 一键上架商品
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(goodsUserInfo.getToken());
            ManageShopBaseQueryResultVO shopBaseQueryResult = goodsCommonMapper.selectByShopId2(userInfo.getShopId());

            // 查询经销商品配置信息
            BaseGoodsConfigVO goodsConfig = goodsCommonMapper.selectDelayGoodsConfig(supplyGoodsCommon.getCommonId());
            // 新增商品
            resultResp = this.addDealerGoodsBatch(userInfo, supplyGoodsCommon,goodsConfig, shopBaseQueryResult, CommonType.supplierGoodsStatus.PUTAWAY.getCode());
            return resultResp;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult dealer(Map<String, String> map) {
        logger.info("map{}",JSON.toJSONString(map));
        ResponseResult resultResp;
        try {
            // 1.根据支付单号查询所有购买商品
            List<DealerOrderGoodsVO> orderGoodsList = JSON.parseArray(map.get("dealerOrderGoodsList"),DealerOrderGoodsVO.class);
            // 2.查询用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token"));
            ManageShopBaseQueryResultVO shopBaseQueryResult = this.baseMapper.selectByShopId2(userInfo.getShopId());

            // 3.校验商品是否已存在  不存在就插入  存在就更新
            List<Integer> supplyGoodsIdList = orderGoodsList.stream().map(DealerOrderGoodsVO::getGoodsId).collect(Collectors.toList());
            DealerGoodsVO dealerGoods = new DealerGoodsVO(userInfo.getShopId(),CommonType.putawayState.NORMAL.getCode(), CommonType.dealerType.BUY.getCode(), supplyGoodsIdList);
            List<DealerPutawayRecordVO> putawayRecordList = this.baseMapper.queryBuyRecordList(dealerGoods);
            Map<Integer, DealerPutawayRecordVO> putawayRecordMap = putawayRecordList.stream().collect(Collectors.toMap(DealerPutawayRecordVO::getSupplyGoodsId, Function.identity()));


            for (DealerOrderGoodsVO orderGoods : orderGoodsList) {
                // 获取经销商品
                GdsBaseDetailResultVO supplyGoodsBase = goodsBaseMapper.selectByGoodsId(orderGoods.getGoodsId());
                // 查询经销商品配置信息
                BaseGoodsConfigVO goodsConfig = this.baseMapper.selectDelayGoodsConfig(supplyGoodsBase.getCommonId());

                DealerPutawayRecordVO putawayRecord = putawayRecordMap.get(orderGoods.getGoodsId());
                if (null != putawayRecord) {
                    supplyGoodsBase.setGoodsStock(orderGoods.getOrderGoodsNum());
                    resultResp = this.updateDealerGoods(putawayRecord, supplyGoodsBase,goodsConfig,CommonType.dealerType.BUY.getCode());
                } else {
                    putawayRecord = new DealerPutawayRecordVO(supplyGoodsBase.getCommonId(), null, userInfo.getShopId(), supplyGoodsBase.getShopId(), CommonType.putawayState.NORMAL.getCode(), CommonType.dealerType.BUY.getCode());
                    putawayRecord =  this.baseMapper.queryPutawayRecord(putawayRecord);
                    if (null != putawayRecord) {
                        // 2.存在其他规格商品  更新common信息 新增goodsBase
                        supplyGoodsBase.setGoodsStock(orderGoods.getOrderGoodsNum());
                        resultResp = this.addDealerGoods(putawayRecord, userInfo, supplyGoodsBase,goodsConfig,CommonType.dealerType.BUY.getCode());
                    } else {
                        // 3.新增商品
                        supplyGoodsBase.setGoodsStock(orderGoods.getOrderGoodsNum());
                        resultResp = this.addDealerGoods(userInfo, supplyGoodsBase, shopBaseQueryResult, goodsConfig,CommonType.dealerType.BUY.getCode());
                        if (resultResp.getCode() == 1) {
                            putawayRecord = (DealerPutawayRecordVO) resultResp.getData();
                        }
                    }
                }
                // 4.新增上架记录
                if (resultResp.getCode() == 1) {
                    DealerPutawayRecordVO addrecord = new DealerPutawayRecordVO(supplyGoodsBase, userInfo, putawayRecord, shopBaseQueryResult);
                    //1 一键上架  2 立即购买
                    addrecord.setDealerType(2);
                    goodsCommonMapper.insertputawayRecord(addrecord);
                }
            }
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateDealerGoods(DealerPutawayRecordVO record,GdsBaseDetailResultVO supplyGoodsBase,BaseGoodsConfigVO goodsConfig,Integer dealerType) {
        try {
            Integer goodsEdit = this.goodsEditCheck(goodsConfig);
            // 1.更新商品状态
            GdbMerchantGoodsCommonVO updateGoods = new GdbMerchantGoodsCommonVO(record.getDealerCommonId(), dealerType.intValue() == CommonType.dealerType.PUT_AWAY.getCode()?1:0, supplyGoodsBase.getGoodsStock(),goodsEdit,null);
            goodsCommonMapper.updateDealerGoods(updateGoods);
            // 2.更新商品状态
            ManageGdsBaseAddParamvDTO gdsBaseAddParam = new ManageGdsBaseAddParamvDTO(record.getDealerGoodsId(), supplyGoodsBase.getCommonId(), supplyGoodsBase.getGoodsStock(), dealerType.intValue() == CommonType.dealerType.PUT_AWAY.getCode()?1:2,dealerType);
            goodsBaseMapper.updateDealerGoodsBase(gdsBaseAddParam);
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addDealerGoods(DealerPutawayRecordVO record,UserInfoVO userInfo,GdsBaseDetailResultVO supplyGoodsBase,BaseGoodsConfigVO goodsConfig,Integer dealerType){
        try {
            Integer goodsEdit = this.goodsEditCheck(goodsConfig);
            // 新增goodsBase
            GoodsBaseVO goodsBase = goodsBaseMapper.queryByGoodsId(supplyGoodsBase.getGoodsId());
            goodsBase.setShopId(userInfo.getShopId());
            goodsBase.setShopName(record.getDealerShopName());
            goodsBase.setCommonId(record.getDealerCommonId());
            goodsBase.setSupplierShopId(goodsBase.getShopId());
            goodsBase.setSupplierGoodsId(goodsBase.getGoodsId());
            goodsBase.setCreateUser(userInfo.getUserName());
            goodsBase.setUpdateUser(userInfo.getUserName());
            goodsBase.setCreateTime(new Date());
            goodsBase.setUpdateTime(new Date());
            goodsBase.setGoodsStock(supplyGoodsBase.getGoodsStock());
            goodsBase.setGoodsIsShelves(dealerType.intValue() == CommonType.dealerType.PUT_AWAY.getCode()?1:2);
            goodsBase.setGoodsId(null);
            goodsBaseMapper.insertDealerGdsBases(goodsBase);
            record.setDealerGoodsId(goodsBase.getGoodsId());
            // 查询当前商品 goodsCommon 规格信息
            Map<String,String> commonSpec = goodsCommonMapper.queryCommonSpecByCommonId(record.getDealerCommonId());
            if(null != commonSpec){
                String commonSpecValue = commonSpec.get("commonSpecValue");
                String specParam = commonSpec.get("specParam");
                // 解析拼接 commonSpecValue
                List<GoodCommonSpecValueJsonBeanVO> goodCommonSpecValueJsonBeans = JSON.parseArray(commonSpecValue,GoodCommonSpecValueJsonBeanVO.class);
                goodCommonSpecValueJsonBeans.add(new GoodCommonSpecValueJsonBeanVO(record.getDealerCommonId(),goodsBase.getGoodsId()));
                commonSpecValue = JSON.toJSONString(goodCommonSpecValueJsonBeans);

                // 已购买商品的 规格信息
                List<GoodSpecValuesJsonBeanVO> goodSpecValues = JSON.parseArray(specParam,GoodSpecValuesJsonBeanVO.class);
                // 商品的 新规格信息
                List<GoodBaseSpecValuesJsonBeanVO> goodBaseSpecValuesJsonBeanList = JSON.parseArray(goodsBase.getSpecValue(),GoodBaseSpecValuesJsonBeanVO.class);
                //将新新增的规格信息 加入goods_common表spec_param
                for (GoodBaseSpecValuesJsonBeanVO goodBaseSpecValuesJsonBean : goodBaseSpecValuesJsonBeanList) {
                    Boolean bool = true;
                    for (GoodSpecValuesJsonBeanVO goodSpecValue : goodSpecValues) {
                        //当规格名相等 进入
                        if(goodBaseSpecValuesJsonBean.getParamName().equals(goodSpecValue.getParamName())){
                            // 循环判断规格值是否相等 相等 结束循环 不相等 新增规格值
                            List<String> paramNameValues = goodSpecValue.getParamNameValues();
                            for (int i = 0; i < paramNameValues.size(); i++) {
                                if(!paramNameValues.get(i).equals(goodBaseSpecValuesJsonBean.getParamValue())){
                                    // 规格值不想等 新增
                                    paramNameValues.add(goodBaseSpecValuesJsonBean.getParamValue());
                                }
                            }
                            goodSpecValue.setParamNameValues(paramNameValues);
                            bool = false;
                        }
                    }
                    //进入 证明 新规格的规格名在 已购买商品的 规格信息中不存在 需新增
                    if(bool){
                        // 当前新规格名都不在老规格中 新增 规格名 规格值
                        GoodSpecValuesJsonBeanVO newGoodsSpec =  new GoodSpecValuesJsonBeanVO();
                        newGoodsSpec.setParamName(goodBaseSpecValuesJsonBean.getParamName());
                        List<String> paramNameValues = new ArrayList<>();
                        paramNameValues.add(goodBaseSpecValuesJsonBean.getParamValue());
                        newGoodsSpec.setParamNameValues(paramNameValues);
                        newGoodsSpec.setSort(1);
                        goodSpecValues.add(newGoodsSpec);
                    }
                }

                specParam = JSON.toJSONString(goodSpecValues);
                //更新common表
                GdbMerchantGoodsCommonVO goodsCommon = new GdbMerchantGoodsCommonVO(record.getDealerCommonId(),dealerType.intValue() == CommonType.dealerType.PUT_AWAY.getCode()?1:0, supplyGoodsBase.getGoodsStock(),goodsEdit,specParam,commonSpecValue);
                goodsCommonMapper.updateDealerGoods(goodsCommon);
            }
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addDealerGoods(UserInfoVO userInfo,GdsBaseDetailResultVO supplyGoodsBase ,ManageShopBaseQueryResultVO shopBaseQueryResult,BaseGoodsConfigVO goodsConfig,Integer dealerType) {
        try {
            Integer goodsEdit = this.goodsEditCheck(goodsConfig);
            GdbMerchantGoodsCommonVO goodsCommon = goodsCommonMapper.selectsupplyGoodsCommonInfo(supplyGoodsBase.getCommonId());
            String commonShopId = goodsCommon.getShopId();
            goodsCommon.setShopId(userInfo.getShopId());
            goodsCommon.setShopName(shopBaseQueryResult.getShopName());
            goodsCommon.setSupplyShopId(commonShopId);
            goodsCommon.setCommonCollect(0);
            goodsCommon.setCommonEvaluate(0);
            goodsCommon.setCommonSalenum(0);
            goodsCommon.setDistrictId(shopBaseQueryResult.getDistrictId());
            goodsCommon.setCommonParentId(goodsCommon.getCommonId());
            goodsCommon.setDeliveryTime(goodsCommon.getDeliveryTime());
            if (goodsCommon.getTransportAreaId() > 0) {
                GdbMerchantTransportAreaVO transportArea = goodsCommonMapper.selectTransportArea(goodsCommon.getTransportAreaId());
                transportArea.setId(null);
                transportArea.setShopId(userInfo.getShopId());
                goodsCommonMapper.insertTransportArea(transportArea);
                goodsCommon.setTransportAreaId(transportArea.getId());
            }
            if (goodsCommon.getTransportTemplate() > 0) {
                GdbMerchantTransportTemplateVO transportTemplate = goodsCommonMapper.selectTransportTemplate(goodsCommon.getTransportTemplate());
                transportTemplate.setId(null);
                transportTemplate.setShopId(userInfo.getShopId());
                goodsCommonMapper.insertTransportTemplate(transportTemplate);
                List<GdbMerchantTransportRuleVO> transportRules = goodsCommonMapper.selectTransportRule(transportTemplate.getId());
                if (!CollectionUtils.isEmpty(transportRules)) {
                    for (GdbMerchantTransportRuleVO transportRule : transportRules) {
                        transportRule.setId(null);
                        transportRule.setTransportTemplateId(transportTemplate.getId());
                    }
                    goodsCommonMapper.insertTransportRule(transportRules);
                }
                goodsCommon.setTransportTemplate(transportTemplate.getId());
            }
            goodsCommon.setCommonUpdateBy(userInfo.getUserId().toString());
            goodsCommon.setOrderOperator(userInfo.getUserName());
            goodsCommon.setCreateUser(userInfo.getUserName());
            goodsCommon.setCommonClick(0);
            goodsCommon.setGoodsType(1);
            goodsCommon.setCommonDistributorFlag(goodsEdit);
            if(dealerType.intValue() == CommonType.dealerType.PUT_AWAY.getCode()) {
                goodsCommon.setDealerGoodsFlag(1);
                goodsCommon.setCommonState(1);
            }else{
                goodsCommon.setDealerGoodsFlag(2);
                goodsCommon.setCommonState(0);
            }
            goodsCommon.setCommonStock(supplyGoodsBase.getGoodsStock());
            goodsCommon.setCommonAddTime(new Date());
            goodsCommon.setCommonSellTime(new Date());
            goodsCommon.setCommonUpdateTime(new Date());
            goodsCommon.setOrderOperatorTime(new Date());
            goodsCommon.setUpdateTime(new Date());
            goodsCommon.setCommonId(null);
            goodsCommon.setCommonVerify(10);
            goodsCommonMapper.insertGoodsCommon(goodsCommon);
            logger.info("添加goodsCommon成功");

            // 添加goodsbase
            GoodsBaseVO goodsBase = goodsBaseMapper.queryByGoodsId(supplyGoodsBase.getGoodsId());
            goodsBase.setGoodsId(null);
            goodsBase.setShopId(userInfo.getShopId());
            goodsBase.setShopName(shopBaseQueryResult.getShopName());
            goodsBase.setCommonId(goodsCommon.getCommonId());
            goodsBase.setSupplierShopId(supplyGoodsBase.getShopId().toString());
            goodsBase.setSupplierGoodsId(supplyGoodsBase.getGoodsId());
            goodsBase.setCreateUser(userInfo.getUserName());
            goodsBase.setUpdateUser(userInfo.getUserName());
            goodsBase.setGoodsStock(supplyGoodsBase.getGoodsStock());
            goodsBase.setCreateTime(new Date());
            goodsBase.setUpdateTime(new Date());
            goodsBase.setGoodsIsShelves(1);
            goodsBaseMapper.insertDealerGdsBases(goodsBase);
            logger.info("添加商品详情成功");

            // 更新规格信息
            List<CommonSpecValueVO> commonSpecValues = Lists.newArrayList();
            CommonSpecValueVO value = new CommonSpecValueVO(goodsBase.getGoodsId(),goodsCommon.getCommonId());
            commonSpecValues.add(value);

            UpdateGdsSpecParamVO updateGdsSpecParam = new UpdateGdsSpecParamVO();
            updateGdsSpecParam.setGoodsId(goodsBase.getGoodsId().toString());
            updateGdsSpecParam.setCommonId(goodsCommon.getCommonId());
            updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));

            List<GoodBaseSpecValuesJsonBeanVO> goodBaseSpecValuesJsonBeanList = JSON.parseArray(goodsBase.getSpecValue(),GoodBaseSpecValuesJsonBeanVO.class);
            List<SpecParamJsonBeanVO> specParamJsonBeanList = new ArrayList<>();
            Map<String,SpecParamJsonBeanVO> specParamMap = new HashMap<>(16);

            for(GoodBaseSpecValuesJsonBeanVO goodsSpecParam : goodBaseSpecValuesJsonBeanList){
                SpecParamJsonBeanVO specParamJsonBean;
                List<String> paramNameValues;

                if(specParamMap.containsKey(goodsSpecParam.getParamName())){
                    specParamJsonBean = specParamMap.get(goodsSpecParam.getParamName());
                    paramNameValues = specParamJsonBean.getParamNameValues();
                    paramNameValues.add(goodsBase.getGoodsSpec());
                    specParamJsonBean.setParamNameValues(paramNameValues);
                }else{
                    paramNameValues = new ArrayList<>();
                    paramNameValues.add(goodsBase.getGoodsSpec());
                    specParamJsonBean = new SpecParamJsonBeanVO(goodsSpecParam.getParamName(),goodsSpecParam.getSort(),paramNameValues);
                }
                specParamMap.put(goodsSpecParam.getParamName(),specParamJsonBean);
            }
            for(String specTemp:specParamMap.keySet()){
                specParamJsonBeanList.add(specParamMap.get(specTemp));
            }

            updateGdsSpecParam.setSpecParam(JSON.toJSONString(specParamJsonBeanList));
            goodsCommonMapper.updateGdsSpec2(updateGdsSpecParam);
            logger.info("更新goodsCommon成功");

            // 添加商品详情
            GdbMerchantGoodsCommonDetailVO commonDetail = goodsCommonDetailMapper.selectByPrimaryKey(supplyGoodsBase.getCommonId());
            if(null != commonDetail) {
                commonDetail.setCommonId(goodsCommon.getCommonId());
                goodsCommonDetailMapper.insertSelective2(commonDetail);
                logger.info("添加商品详情成功");
            }
            // 添加商品图片
            List<GdbMerchantGoodsImagesVO> goodsImages = goodsImagesMapper.selectByCommonId2(supplyGoodsBase.getCommonId());
            if (!CollectionUtils.isEmpty(goodsImages)) {
                for (GdbMerchantGoodsImagesVO goodsImage : goodsImages) {
                    goodsImage.setCommonId(goodsCommon.getCommonId());
                    goodsImage.setShopId(userInfo.getShopId());
                }
                goodsImagesMapper.insertBatch2(goodsImages);
                logger.info("添加商品图片成功");
            }
            DealerPutawayRecordVO record = new DealerPutawayRecordVO(goodsBase.getCommonId(),goodsBase.getGoodsId(),goodsBase.getShopId(),goodsBase.getShopName());
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg(),record);
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult goodsPutawayBatch(DealerGoodsUserInfoDTO goodsUserInfo) {
        ResponseResult resultResp = ResponseResult.success();
        try {
            // 一键上架商品
            List<ManageGdsCommonResultVO> commonResults = goodsCommonMapper.queryCommonInfoList(goodsUserInfo.getCommonIdList());
            // 获取用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(goodsUserInfo.getToken());
            ManageShopBaseQueryResultVO shopBaseQueryResult = goodsCommonMapper.selectByShopId2(userInfo.getShopId());
            for(ManageGdsCommonResultVO supplyGoodsCommon : commonResults) {
                BaseGoodsConfigVO goodsConfig = goodsCommonMapper.selectDelayGoodsConfig(supplyGoodsCommon.getCommonId());
                // 新增商品
                resultResp = this.addDealerGoodsBatch(userInfo, supplyGoodsCommon,goodsConfig, shopBaseQueryResult, CommonType.supplierGoodsStatus.PUTAWAY.getCode());
            }
            return resultResp;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addDealerGoodsBatch(UserInfoVO userInfo,ManageGdsCommonResultVO supplyGoodsCommon,BaseGoodsConfigVO goodsConfig ,ManageShopBaseQueryResultVO shopBaseQueryResult,Integer dealerType) {
        try {
            Integer goodsEdit = this.goodsEditCheck(goodsConfig);
            GdbMerchantGoodsCommonVO goodsCommon = goodsCommonMapper.selectsupplyGoodsCommonInfo(supplyGoodsCommon.getCommonId());
            String commonShopId = goodsCommon.getShopId();
            goodsCommon.setShopId(userInfo.getShopId());
            goodsCommon.setShopName(shopBaseQueryResult.getShopName());
            goodsCommon.setSupplyShopId(commonShopId);
            goodsCommon.setCommonCollect(0);
            goodsCommon.setCommonEvaluate(0);
            goodsCommon.setCommonSalenum(0);
            goodsCommon.setDistrictId(shopBaseQueryResult.getDistrictId());
            goodsCommon.setCommonParentId(goodsCommon.getCommonId());
            goodsCommon.setCommonUpdateBy(userInfo.getUserId().toString());
            goodsCommon.setOrderOperator(userInfo.getUserName());
            goodsCommon.setCreateUser(userInfo.getUserName());
            goodsCommon.setCommonClick(0);
            goodsCommon.setGoodsType(1);
            goodsCommon.setCommonDistributorFlag(goodsEdit);
            if (dealerType.intValue() ==  CommonType.supplierGoodsStatus.PUTAWAY.getCode()) {
                goodsCommon.setDealerGoodsFlag(1);
                goodsCommon.setCommonState(1);
            } else {
                goodsCommon.setDealerGoodsFlag(2);
                goodsCommon.setCommonState(0);
            }
            goodsCommon.setCommonStock(supplyGoodsCommon.getCommonStock());
            goodsCommon.setCommonAddTime(new Date());
            goodsCommon.setCommonSellTime(new Date());
            goodsCommon.setCommonUpdateTime(new Date());
            goodsCommon.setOrderOperatorTime(new Date());
            goodsCommon.setUpdateTime(new Date());
            goodsCommon.setCommonId(null);
            goodsCommon.setCommonVerify(10);
            goodsCommonMapper.insertGoodsCommon(goodsCommon);

            // 添加goodsbase
            List<GoodsBaseVO> goodsBaseList = goodsBaseMapper.queryGoodsCommonId(supplyGoodsCommon.getCommonId());
            Integer supplyGoodsId;
            for (GoodsBaseVO goodsBase : goodsBaseList) {
                supplyGoodsId = goodsBase.getGoodsId();
                goodsBase.setGoodsId(null);
                goodsBase.setSupplierShopId(commonShopId);
                goodsBase.setSupplierGoodsId(supplyGoodsId);
                goodsBase.setShopId(userInfo.getShopId());
                goodsBase.setShopName(shopBaseQueryResult.getShopName());
                goodsBase.setCommonId(goodsCommon.getCommonId());
                goodsBase.setCreateUser(userInfo.getUserName());
                goodsBase.setUpdateUser(userInfo.getUserName());
                goodsBase.setGoodsStock(goodsBase.getGoodsStock());
                goodsBase.setCreateTime(new Date());
                goodsBase.setUpdateTime(new Date());
                if (dealerType.intValue() == CommonType.supplierGoodsStatus.PUTAWAY.getCode()) {
                    goodsBase.setGoodsIsShelves(1);
                } else {
                    goodsBase.setGoodsIsShelves(2);
                }
            }
            goodsBaseMapper.insertGoodsBase(goodsBaseList);
            // 获取最新商品
            goodsBaseList = goodsBaseMapper.queryGoodsCommonId(goodsCommon.getCommonId());
            List<CommonSpecValueVO> commonSpecValues = Lists.newArrayList();
            for(GoodsBaseVO goodsBase : goodsBaseList) {
                CommonSpecValueVO value = new CommonSpecValueVO(goodsBase.getGoodsId(), goodsCommon.getCommonId());
                commonSpecValues.add(value);
            }

            UpdateGdsSpecParamVO updateGdsSpecParam = new UpdateGdsSpecParamVO();
            updateGdsSpecParam.setGoodsId(goodsBaseList.get(0).getGoodsId().toString());
            updateGdsSpecParam.setCommonId(goodsCommon.getCommonId());
            updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));
            goodsCommonMapper.updateGdsSpec2(updateGdsSpecParam);

            // 添加商品详情
            GdbMerchantGoodsCommonDetailVO commonDetail = goodsCommonDetailMapper.selectByPrimaryKey(supplyGoodsCommon.getCommonId());
            if(null != commonDetail) {
                commonDetail.setCommonId(goodsCommon.getCommonId());
                goodsCommonDetailMapper.insertSelective2(commonDetail);
            }
            // 添加商品图片
            List<GdbMerchantGoodsImagesVO> goodsImages = goodsImagesMapper.selectByCommonId2(supplyGoodsCommon.getCommonId());
            if (!CollectionUtils.isEmpty(goodsImages)) {
                for (GdbMerchantGoodsImagesVO goodsImage : goodsImages) {
                    goodsImage.setCommonId(goodsCommon.getCommonId());
                    goodsImage.setShopId(userInfo.getShopId());
                }
                goodsImagesMapper.insertBatch2(goodsImages);
            }
            DealerPutawayRecordVO record = new DealerPutawayRecordVO(supplyGoodsCommon, goodsCommon, userInfo, shopBaseQueryResult);
            // 1 是  2 否 未修改价格的商品不展示
            record.setIsPriceUpdate(2);
            goodsCommonMapper.insertputawayRecord(record);
            return ResponseResult.success();
        } catch (Exception e) {
            throw  e;
        }
    }
    /**
     * 商品内容更新校验
     * @param goodsConfig
     * @return
     */
    private Integer goodsEditCheck(BaseGoodsConfigVO goodsConfig){
        Integer goodsEdit;
        if(goodsConfig.getSellEdit().intValue() == 2){
            goodsEdit = 2;
        }else{
            if(goodsConfig.getSellEditPrice().intValue() == 1){
                goodsEdit = 0;
            }else{
                goodsEdit = 1;
            }
        }
        return  goodsEdit;
    }

    @Override
    public ResponseResult queryCouponList(UserVcBaseQueryDTO param) {

        List<WapCommonBaseUserFootVO> goodsList = null;
        List<Integer> goodsCatLimitList = goodsCommonMapper.queryCouponList(param);

        if (!CollectionUtils.isEmpty(goodsCatLimitList)) {
            goodsList = goodsCommonMapper.selectByCommonIds4(goodsCatLimitList);
        }
        if (CollectionUtils.isEmpty(goodsList)) {
            goodsList = Lists.newArrayList();
        }

        // 处理活动价格
        for (WapCommonBaseUserFootVO gdsListQueryResult : goodsList) {
            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(
                    Integer.parseInt(gdsListQueryResult.getGoodsId()), gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && !activityGoodsDetail.equals("")
                    && activityGoodsDetail.getActivityStatus() != 0) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if(activityGoodsDetail.getActivityStatus() == 5){
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(0);
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(0);
            }
        }

        return ResponseResult.success(goodsList);
    }

    @Override
    public ResponseResult queryRedPacketList(UserAvailableRedpacketQueryDTO param) {
        // 查询模板详情
        YfRedpacketTemplateVO redpacketTemplate = goodsCommonMapper.selectByRedpacketId(param);

        List<WapHallGoodsQueryVO> goodsList = null;
        if (null != redpacketTemplate && redpacketTemplate.getManyRedpacketType().equals(1)) {
            String goodsCatLimit = redpacketTemplate.getGoodsCatLimit();
            if (null != goodsCatLimit && !goodsCatLimit.equals("")) {
                List<Integer> goodsCatLimitList = JsonUtils.StringToList2(goodsCatLimit);

                goodsList = goodsBaseMapper.selectByGoodsIds(goodsCatLimitList);
            }
        }
        if (CollectionUtils.isEmpty(goodsList)) {
            goodsList = Lists.newArrayList();
        }
        // 处理活动价格
        for (WapHallGoodsQueryVO gdsListQueryResult : goodsList) {
            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsId(),
                    gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if(activityGoodsDetail.getActivityStatus() == 5){
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(0);
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(0);
            }
        }
        return ResponseResult.success(goodsList);
    }

    @Override
    public ResponseResult queryIntegralAll(ListPageQueryParamDTO param) {
        Map<String,Object> map = new HashMap<>();
        try {
            // 获取分类id
            if (null != param.getCatId()) {
                GoodsCatSearchChildVO goodsCatSearchChild = null;
                List<WebCatMenuVO> allMenu = null;
                List<Integer> catIds = null;
                // 从缓存中获取
                String cacheCatIds = RedisUtil.get(Constants.CACHE_GOODS_WAP_GOODS_LIST_PREFIX + "_" + param.getCatId());

                if (null != cacheCatIds && !cacheCatIds.equals("")) {
                    goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
                    catIds = goodsCatSearchChild.getCatIds();
                } else {
                    // 查询所有下级分类
                    allMenu = goodsCatMapper.selectAllCat();
                    catIds = getMenuList(allMenu, param.getCatId());

                    goodsCatSearchChild = new GoodsCatSearchChildVO();
                    goodsCatSearchChild.setAllMenu(allMenu);
                    goodsCatSearchChild.setCatIds(catIds);
                    RedisUtil.set(Constants.CACHE_GOODS_WAP_GOODS_LIST_PREFIX + "_" + param.getCatId(),
                            JsonUtils.toString(goodsCatSearchChild),RedisUtil.EXRP_MONTH);
                }
                if (!CollectionUtils.isEmpty(catIds)) {
                    catIds.add(param.getCatId());
                    param.setCatIds(catIds);
                }
            }
            //将对象转换为map
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            IPage<IntegralGoodsResultVO> page = this.baseMapper.queryIntegralAll(new Query<IntegralGoodsResultVO>().getPage(data),param);
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult platformLockUpdate(PlatFormGoodsStateDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            Map<String, Object> map = new HashMap<>();
            List<Integer> list = new ArrayList<>();
            this.baseMapper.updateGoodsLock(param);
            if (null != param.getCommonIsScreen() && CommonType.commonSpuState.GOODS_LOCK.getCode().equals(param.getCommonIsScreen())) {
                // 1 是添加  2是删除    屏蔽
                map.put("type", CommonType.operateStatus.DEL.getCode());
            } else {
                // 1 是添加  2是删除    不屏蔽
                map.put("type", CommonType.operateStatus.ADD.getCode());
            }
            list = param.getCommonIdList();
            //通过mq 更新es的商品数据
            map.put("commonIdS", list);
            MqSendUtils.mqSendGoodsByEs(map);
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult platformScreenUpdate(PlatFormGoodsStateDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            Map<String, Object> map = new HashMap<>();
            this.baseMapper.updateGoodsScreen(param);
            if (null != param.getCommonIsScreen() && CommonType.commonSpuState.GOODS_SHIELD.getCode().equals(param.getCommonIsScreen())) {
                // 1 是添加  2是删除    屏蔽
                map.put("type", CommonType.operateStatus.DEL.getCode());
            } else {
                // 1 是添加  2是删除    不屏蔽
                map.put("type", CommonType.operateStatus.ADD.getCode());
            }
            List<Integer> list = this.baseMapper.queryAllGoodsIdByCommonId(param.getCommonIdList());
            //list = param.getCommonIdList();
            //通过mq 更新es的商品数据
            map.put("commonIdS", list);
            MqSendUtils.mqSendGoodsByEs(map);
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);


    }

    @Override
    public ResponseResult platformViolationsUpdate(PlatFormGoodsStateDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        Map<String, Object> map = new HashMap<>();
        if (null != userInfo) {
            //操作人
            param.setOrderOperator(userInfo.getUserRealname());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //操作时间
            String finishTime = dateFormat.format(new Date());
            param.setOrderOperatorTime(finishTime);
            //审核时间
            param.setCommonVerifyTime(new Date());
            //修改审核状态
            this.baseMapper.updateGoodsState(param);
            //获取商品id集合
            List<Integer> list = param.getCommonIdList();
            ArrayList<Integer> goodsIdList = new ArrayList<>();
            //审核通过，更新分销商品列表数据
            for (Integer commonId : list) {
                List<Integer> goodsIds = goodsBaseMapper.selectList(new LambdaQueryWrapper<GoodsBaseEntity>()
                                        .eq(GoodsBaseEntity::getCommonId,commonId))
                                        .stream().map(GoodsBaseEntity::getGoodsId).collect(Collectors.toList());
                goodsIdList.addAll(goodsIds);
            }
            //通过mq 更新es的商品数据
            map.put("goodsIdS", goodsIdList);
            //上 下 架
            if (null != param.getCommonState()) {
                //上架
                if (param.getCommonState().equals(CommonType.goodsIsShelves.GOODS_ON_THE_SHELF.getCode())) {
                    // 1 是添加  2是删除
                    map.put("type", CommonType.operateStatus.ADD.getCode());
                    for (Integer commonId : list) {
                        // 查询代发商品 所同步的供应商商品是否在售
                        Integer supplierGoodsStart = goodsCommonMapper.querySupplierGoodsStart(commonId);
                        if(0 < supplierGoodsStart){
                            // 商品 不在售 所有经销商品不能 上架
                            return ResponseResult.fail(2,"有商品在供应商端未在售，商品不能上架!");
                        }
                    }
                    goodsBaseMapper.updateGoodsBaseStateList(param);
                }
                //下架
                if (param.getCommonState().equals(CommonType.goodsIsShelves.GOODS_OFF_THE_SHELF.getCode())) {
                    // 1 是添加  2是删除
                    map.put("type", CommonType.operateStatus.DEL.getCode());
                    param.setCommonState(CommonType.commonSpuState.GOODS_OFF_SHELF.getCode());
                    goodsBaseMapper.updateGoodsBaseStateList(param);
                    List<Integer> supperCommonids = new ArrayList<>();
                    for (Integer SuppercommonId : list) {
                        //判断当前是否是是供应商商品 如果是 下架商家对应的商品 并更新es
                        List<Integer> dealerCommonIds = goodsCommonMapper.queryIsSupperGoods(SuppercommonId);
                        if(null != dealerCommonIds && dealerCommonIds.size() > 0){
                            //当前商品是供应商商品 所有商家商品下架 更新es
                            PlatFormGoodsStateDTO dealerGoodsParam = new PlatFormGoodsStateDTO();
                            dealerGoodsParam.setCommonIdList(dealerCommonIds);
                            dealerGoodsParam.setCommonState(param.getCommonState());
                            goodsCommonMapper.updateGoodsState(dealerGoodsParam);

                            supperCommonids.addAll(dealerCommonIds);
                        }
                    }
                    list.addAll(supperCommonids);
                }
                //禁售
                if (param.getCommonState().equals(CommonType.commonSpuState.GOODS_ILLEGAL.getCode())) {
                    // 1 是添加  2是删除
                    map.put("type", CommonType.operateStatus.DEL.getCode());
                }
            }
            //审核
            if (null != param.getCommonVerify()) {
                //通过
                if (1 == param.getCommonVerify()) {
                    // 1 是添加  2是删除
                    map.put("type", CommonType.operateStatus.ADD.getCode());
                } else {// 未通过 审核中
                    // 1 是添加  2是删除
                    map.put("type", CommonType.operateStatus.DEL.getCode());
                }
            }
            MqSendUtils.mqSendGoods(map);

            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);

    }

    @Override
    public ResponseResult platformQueryDetail(ManageGdsNameQueryParamDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            Integer commonId = param.getCommonId();
            if (null == commonId) {
                return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
            }
            // 查询公共信息
            ManageGdsCommonVO common = this.baseMapper.selectByCommonIdInfo(commonId);
            if (null == common) {
                return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);

            }
            // 查询商品所有规格
            List<ManageGdsBaseAddResultVO> goodsBaseList = goodsBaseMapper.selectByCommonId(commonId);

            // 查询所有属性
            List<ManageGoodsPropertyAddVO> propertys = goodsPropertyMapper.selectByCommonId(commonId);
            if (CollectionUtils.isEmpty(propertys)) {
                // 根据typeId查询属性名
                List<GoodsPropertyEntity> goodsPropertys = goodsPropertyMapper.selectList(new LambdaQueryWrapper<GoodsPropertyEntity>()
                                                            .eq(GoodsPropertyEntity::getTypeId, common.getTypeId())
                                                            .orderByAsc(GoodsPropertyEntity::getPropertyDisplayorder));
                for (GoodsPropertyEntity propertyName : goodsPropertys) {
                    ManageGoodsPropertyAddVO propertyAdd = new ManageGoodsPropertyAddVO();
                    propertyAdd.setPropertyId(propertyName.getPropertyId());
                    propertyAdd.setPropertyName(propertyName.getPropertyName());
                    propertys.add(propertyAdd);
                }
            }
            common.setCommonProperty(JsonUtils.toString(propertys));
            // 设置运费和售卖区域
            ResponseResult transportTemplate = businessServiceClient.selectTemplateById(common.getTransportTemplate());
            ManageTransportTemplateVO transportTemplates=JSON.parseObject(JSON.toJSONString(transportTemplate.getData()),ManageTransportTemplateVO.class);

            ResponseResult areas = businessServiceClient.selectAreaById(common.getTransportAreaId());
            ManageTransportAreaVO transportAreas=JSON.parseObject(JSON.toJSONString(areas.getData()),ManageTransportAreaVO.class);
            common.setTransportTemplates(transportTemplates);
            common.setTransportAreas(transportAreas);

            // 处理店铺自定义分类
            List<ManageGoodsSelfCatVO> shopSelfCats = null;
            if (null != common.getShopCatId() && !common.getShopCatId().equals("")) {
                shopSelfCats = this.baseMapper.selectByShopCatId(JsonUtils.StringToList(common.getShopCatId()));
            }
            common.setShopSelfCat(shopSelfCats);

            // 商品详细介绍
            GoodsCommonDetailEntity goodsCommonDetail = goodsCommonDetailMapper.selectById(commonId);
            // 商品图片组
            List<GoodsImagesEntity> goodsImages = goodsImagesMapper.selectList(new LambdaQueryWrapper<GoodsImagesEntity>()
                                                .eq(GoodsImagesEntity::getCommonId,commonId)
                                                .eq(GoodsImagesEntity::getShopId,param.getShopId()));


            // 查询关联板式
            Integer commonFormatidTopId = common.getCommonFormatidTop();
            Integer commonFormatidBottomId = common.getCommonFormatidBottom();
            BaseFormatVO commonFormatidTop = null;
            BaseFormatVO commonFormatidBottom = null;
            if (null != commonFormatidTopId) {
                commonFormatidTop =  this.baseMapper.selectBaseFormatById(commonFormatidTopId);
            }
            if (null != commonFormatidBottomId) {
                commonFormatidBottom =this.baseMapper.selectBaseFormatById(commonFormatidBottomId);
            }
            BaseGoodsConfigVO manageGdsGoodsConfig = this.baseMapper.selectoodsConfigByPrimaryKey(commonId);


            Map<String, Object> map=new HashMap<>();
            map.put("common",common);
            map.put("commonFormatidBottom",commonFormatidBottom);
            map.put("commonFormatidTop",commonFormatidTop);
            map.put("goodsBaseList",goodsBaseList);
            map.put("goodsCommonDetail",goodsCommonDetail);
            map.put("goodsImages",goodsImages);
            map.put("manageGdsGoodsConfig",manageGdsGoodsConfig);

            return ResponseResult.success(map);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryGateCommonsList(GateQueryCommonsDTO param) {

        try {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
            if (userInfo == null) {
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
            }
            //Integer integer = this.baseMapper.queryShopIdByGateId(userInfo.getShopId());
            param.setShopId(Integer.parseInt(userInfo.getShopId()));
            Page<GateQueryCommonsVO> page = new Page<>(param.getPage(),param.getLimit());
            IPage<GateQueryCommonsVO> commonsResults = this.baseMapper.queryGateCommonsList(page,param);
            commonsResults.getRecords().forEach(commomResult -> {
                Integer shopStock = 0;
                List<GateGoodsBaseVO> GateGoodsBases = this.baseMapper.queryGateGoodsBasePoList(userInfo.getShopId(), commomResult.getCommonId());
                if (null != GateGoodsBases) {
                    List<Integer> integerList = GateGoodsBases.stream().map(GdbGateGoodsBasePo -> GdbGateGoodsBasePo.getShopGateGoodsStock()).collect(Collectors.toList());
                    Integer sum = integerList.stream().reduce(Integer::sum).orElse(0);
                    shopStock = sum;
                }
                commomResult.setShopGateGoodsStock(shopStock);
            });
            return ResponseResult.success(PageUtils.getPage(commonsResults));
        } catch (Exception e) {
            return ResponseResult.fail(500,e.getMessage());
        }
    }

    @Override
    public ResponseResult queryGoodsSpecList(ManageCommonIdsDTO param) {
        // 权限判断
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.getToken());

        if (null == userInfoStr) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        try {
            List<ManageGoodsBaseListVO> goodsBases = new ArrayList<ManageGoodsBaseListVO>();
            GateGoodsBaseVO gdbGateGoodsBasePo = null;
            UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
            UserInfoVO userInfo = dto.getUser();
            goodsBases = this.baseMapper.queryGoodsSpecList(param.getCommonId());
            for (ManageGoodsBaseListVO goodsBase : goodsBases) {
                gdbGateGoodsBasePo = new GateGoodsBaseVO();
                gdbGateGoodsBasePo.setCommonId(goodsBase.getCommonId());
                gdbGateGoodsBasePo.setGoodsId(goodsBase.getGoodsId());
                gdbGateGoodsBasePo.setShopGateId(Integer.valueOf(userInfo.getShopId()));
                goodsBase.setGoodsSpec(goodsBase.getGoodsSpec());
                //查询当前商品门店设置的库存
                Integer shopGateGoodsStock = this.baseMapper.queryGoodsGateStock(goodsBase.getGoodsId(),userInfo.getShopId());
                if (null == shopGateGoodsStock) {
                    goodsBase.setShopGateGoodsStock(0);
                }else {
                    goodsBase.setShopGateGoodsStock(shopGateGoodsStock);
                }
            }
            return ResponseResult.success(goodsBases);
        } catch (Exception e) {
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult updateGateShopStock(GateUpShopGoodsStockDTO param) {
        // 权限判断
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.getToken());
        if (null == userInfoStr) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        if (param.getCommonId() == null) {
            return ResponseResult.fail(2, "commonId不能为null");
        }
        if (param.getGoodsId() == null) {
            return ResponseResult.fail(2, "goodsId不能为空");
        }
        GateGoodsBaseVO gdbGateGoodsBasePo = new GateGoodsBaseVO();
        Integer integer = null;
        // 根据goodsID 获取门店总和最大值
        Integer goodsShopGateStock = this.baseMapper.queryGateGoodsStock(param);
        try {
            UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
            UserInfoVO userInfo = dto.getUser();
            //根据shopId，commonid,goodsId 获取所有门店商品数量总和
            // 判断是否添加过门店库存
            gdbGateGoodsBasePo.setShopId(Integer.valueOf(userInfo.getShopId()));
            gdbGateGoodsBasePo.setShopGateId(Integer.valueOf(userInfo.getShopGateId()));
            gdbGateGoodsBasePo.setGoodsId(param.getGoodsId());
            gdbGateGoodsBasePo.setCommonId(param.getCommonId());
            gdbGateGoodsBasePo.setShopGateGoodsStock(param.getGoodsShopGateStock());
            Integer count = this.baseMapper.queryGateGoodsCount(gdbGateGoodsBasePo);
            if (count > 0) {
                //获取当前门店库存
                Integer stock = this.baseMapper.queryGateShopStock(gdbGateGoodsBasePo);
                if (param.getGoodsShopGateStock() < stock || param.getGoodsShopGateStock() <= goodsShopGateStock) {
                    // 增加或减少多少库存
                    Integer upStock = stock - param.getGoodsShopGateStock();
                    integer = this.baseMapper.updateGateGoodsBase(gdbGateGoodsBasePo);

                    Integer goodsstock = goodsShopGateStock + upStock;
                    Integer integer1 = this.baseMapper.updateGoodsStock(goodsstock, param.getGoodsId());

                    if (integer > 0 && integer1 > 0) {
                        return ResponseResult.success("库存设置成功", integer);
                    }
                }
                return ResponseResult.fail(2, "库存设置超过上限");
            }else {
                integer = this.baseMapper.insertGateGoodsBase(gdbGateGoodsBasePo);
                Integer stock = goodsShopGateStock - param.getGoodsShopGateStock();
                if (integer > 0) {
                    //修改goodsBase库存
                    this.baseMapper.updateGoodsBaseStock(stock, param.getGoodsId());
                    return ResponseResult.success("库存设置成功", integer);
                }
                return ResponseResult.fail(2, "库存设置超过上限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(2, "设置出错，联系管理员");
        }
    }

    @Override
    public ResponseResult checkBatchVerify(DealerGoodsUserInfoDTO dto) {
        UserInfoVO userInfo =  ParseTokenUtils.getUserInfoByToken(dto.getToken());
        List<GoodsCommonEntity> gdsCommonResultList = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsCommonEntity>()
                                                      .eq(GoodsCommonEntity::getShopStatus,CommonType.shopStatus.STORE_OPEN_SUCCESS.getCode())
                                                      .eq(GoodsCommonEntity::getCommonState,CommonType.commonSpuState.GOODS_NORMAL.getCode())
                                                      .eq(GoodsCommonEntity::getCommonVerify,CommonType.productReview.PASS.getCode())
                                                      .in(GoodsCommonEntity::getCommonId,dto.getCommonIdList()));
        Map<Integer, GoodsCommonEntity> gdsCommonResultMap = gdsCommonResultList.stream().collect(Collectors.toMap(GoodsCommonEntity::getCommonId, Function.identity()));
        for (Integer commonId : dto.getCommonIdList()) {
            // 1.查询商品所属分类
            List<ShopGoodsCatVO> goodsCatList = this.baseMapper.queryByCommonId(commonId);
            if (!CollectionUtils.isEmpty(goodsCatList)) {
                GoodsCommonEntity gdsCommonResult = gdsCommonResultMap.get(commonId);
                // 3.查询商家申请的分类结果
                List<ManageGoodsSelfCatVO> passShopCat =  this.baseMapper.queryShopDealerCatList(gdsCommonResult.getShopId(), CommonType.dealerStatus.AUTH_PASS.getCode(), userInfo.getShopId());
                Boolean flag = this.queryGoodsCat(passShopCat, goodsCatList);
                if (flag) {
                    return ResponseResult.success();
                } else {
                    return ResponseResult.fail(0, "商品"+gdsCommonResult.getCommonName()+BizCodeEnume.CAT_NO_AUTH.getMsg());
                }
            }
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult checkDealer(DealerGoodsUserInfoDTO dto) {
        UserInfoVO userInfo =  ParseTokenUtils.getUserInfoByToken(dto.getToken());
        String shopId = userInfo.getShopId();
        // 查询要经销的商品
        GdsBaseDetailResultVO supplyGoodsBase = null;
        if(null == dto.getCommonId()) {
            supplyGoodsBase = goodsBaseMapper.selectByGoodsId(dto.getGoodsId());
            dto.setCommonId(supplyGoodsBase.getCommonId());
        }
        //判断是否是自己的商品
        Integer count = goodsBaseMapper.isMeGoods(shopId,dto.getCommonId());
        if(null!= count && count >= 1){
            return ResponseResult.fail(BizCodeEnume.GOODS_NOT_WORKING);
        }
        // 判断是否需要申请经销商
        BaseGoodsConfigVO manageGdsGoodsConfig = this.baseMapper.selectDelayGoodsConfig(dto.getCommonId());
        DealerApplyInfoVO dealerApplyInfo;
        if (manageGdsGoodsConfig.getSellCheck().intValue() == 1) {
            dto.setSellDeliver(manageGdsGoodsConfig.getSellDeliver());
            ResponseResult resultResp = this.queryGoodsUser(dto);
            if (resultResp.getCode()!=CommonStatusEnum.SUCCESS.getCode()) {
                return resultResp;
            } else {
                dealerApplyInfo = JSON.parseObject(JSON.toJSONString(resultResp.getData()), DealerApplyInfoVO.class);
            }

            return ResponseResult.success(supplyGoodsBase);

        } else {
            //根据commonid查询出对应供应商的goodsid和shopid
            List<Integer> list =  this.baseMapper.selectShopIdAndGoodsId(dto.getCommonId());
            if(null != list && list.size()>0){
                //判读该商家是否已经同步过商品
                Integer countSys = goodsBaseMapper.selectCount(new LambdaQueryWrapper<GoodsBaseEntity>()
                                   .eq(GoodsBaseEntity::getShopId,shopId)
                                   .eq(GoodsBaseEntity::getSupplierGoodsId,list.get(0)));
                if(null != countSys && countSys >= 1){
                    return ResponseResult.fail(BizCodeEnume.PRODUCT_CANNOT_BE_SYNCHRONIZED_REPEATEDLY);
                }
            }else{
                return ResponseResult.fail(BizCodeEnume.INTERNAL_ERROR);
            }

            return ResponseResult.success(supplyGoodsBase);
        }
    }

    @Override
    public ResponseResult queryGoodsUser(DealerGoodsUserInfoDTO dto){
        UserInfoVO userInfo =  ParseTokenUtils.getUserInfoByToken(dto.getToken());
        if(null == userInfo){
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }else if(null == userInfo.getShopType() || userInfo.getShopType().intValue() != 1){
            return ResponseResult.fail(BizCodeEnume.USER_IS_NOT_BUSINESS);
        }
        Integer supplyShopId;
        Integer supplyGoodsId = null;
        if(null != dto.getCommonId()){
            GoodsCommonEntity goodsCommon =  this.baseMapper.selectById(dto.getCommonId());
            supplyShopId=goodsCommon.getShopId();
        }else{
            GdsBaseDetailResultVO goodsBase =  goodsBaseMapper.selectByGoodsId(dto.getGoodsId());
            dto.setCommonId(goodsBase.getCommonId());
            supplyShopId= goodsBase.getShopId();
            supplyGoodsId = goodsBase.getGoodsId();
        }
        dto.setSupplierShopId(supplyShopId);
        dto.setDealerShopId(userInfo.getShopId());
        dto.setDealerStatus(CommonType.dealerStatus.AUTH_PASS.getCode());
        DealerApplyInfoVO dealerApplyInfo = baseServiceClient.queryDealerApplyByShop(dto);
        if(null == dealerApplyInfo){
            return ResponseResult.fail(BizCodeEnume.NOT_APPLYING_FOR_A_DISTRIBUTOR);
        }else{
            if(dto.getSellDeliver().equals(CommonType.dealerType.PUT_AWAY.getCode())) {
                // 校验商品是否已经销
                DealerPutawayRecordVO record = new DealerPutawayRecordVO(dto.getCommonId(),supplyGoodsId, userInfo.getShopId(), supplyShopId, CommonType.putawayState.NORMAL.getCode(), CommonType.dealerType.PUT_AWAY.getCode());
                record = this.baseMapper.queryPutawayRecord(record);

                if( record == null){
                    return ResponseResult.success(dealerApplyInfo);
                }else{
                    return ResponseResult.fail(BizCodeEnume.GOODS_DEALER);
                }
            }
            return ResponseResult.success(dealerApplyInfo);
        }
    }

    @Override
    public ResponseResult queryGoodsDetailByBusiness(ManageCommonIdsDTO dto) {
        // 查询商品详情
        GoodsCommonEntity goodsCommon = goodsCommonMapper.selectById(dto.getCommonId());
        if (null == goodsCommon) {
            return ResponseResult.fail(BizCodeEnume.GOODS_NOT_EXIST);
        }
        // 运费规则
        ManageTransportAreaVO transportArea = this.baseMapper.selectByPrimaryKey(goodsCommon.getTransportAreaId());
        SupplyGoodsDetailVO supplyGoodsDetail = new SupplyGoodsDetailVO(goodsCommon,transportArea.getName());
        // 不同规则商品
        List<GoodsBaseEntity> goodsSpecList = goodsBaseMapper.selectList(new LambdaQueryWrapper<GoodsBaseEntity>()
                                              .eq(GoodsBaseEntity::getCommonId,goodsCommon.getCommonId()));
        // 查询图片信息
        List<GoodsImagesEntity> goodsImages = goodsImagesMapper.selectList(new LambdaQueryWrapper<GoodsImagesEntity>()
                                                .eq(GoodsImagesEntity::getCommonId,goodsCommon.getCommonId()));
        if (CollectionUtils.isEmpty(goodsImages)) {
            GoodsImagesEntity goodsImage = new GoodsImagesEntity();
            goodsImage.setImagesImage(goodsCommon.getCommonImage());
            goodsImage.setImagesDisplayorder(0);
            goodsImage.setImagesIsDefault(1);
            goodsImages.add(goodsImage);
        }
        GoodsCommonDetailEntity detail = goodsCommonDetailMapper.selectById(goodsCommon.getCommonId());
        logger.info("detail{}",detail);

        supplyGoodsDetail.setCommonBody(detail.getCommonBody());
        supplyGoodsDetail.setGoodsSpecList(goodsSpecList);
        supplyGoodsDetail.setGoodsImages(goodsImages);

        return ResponseResult.success(supplyGoodsDetail);
    }

    @Override
    public ResponseResult queryGoodsListByBusiness(WebGoodsListQueryDTO dto) throws IllegalAccessException {

        // 获取分类id
        GoodsCatSearchChildVO goodsCatSearchChild;
        List<WebCatMenuVO> allMenu;
        List<Integer> catIds;

        //获取登录用户信息
        UserInfoVO userInfo =  ParseTokenUtils.getUserInfoByToken(dto.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }

        if (null != dto.getCatId()) {
            // 从缓存中获取
            String cacheCatIds = RedisUtil.get(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + dto.getCatId());
            if (null != cacheCatIds && !cacheCatIds.equals("")) {
                goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
                catIds = goodsCatSearchChild.getCatIds();
            } else {
                allMenu = goodsCatMapper.selectAllCat();
                catIds = this.getMenuList(allMenu, dto.getCatId());
                goodsCatSearchChild = new GoodsCatSearchChildVO();
                goodsCatSearchChild.setAllMenu(allMenu);
                goodsCatSearchChild.setCatIds(catIds);
                RedisUtil.set(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + dto.getCatId(), JsonUtils.toString(goodsCatSearchChild), RedisUtil.EXRP_MONTH);
            }
            if (!CollectionUtils.isEmpty(catIds)) {
                catIds.add(dto.getCatId());
                dto.setCatIds(catIds);
                dto.setCatId(0);
            }
        }
        dto.setShopId(Integer.valueOf(userInfo.getShopId()));
        Map data= ParseMapUtils.beanToMap(dto);
        // 查询商品列表
        IPage<GdsListQueryResultVO> page=this.baseMapper.selectSupplyWebFilter(new Query<GdsListQueryResultVO>().getPage(data), dto);

        if(!CollectionUtils.isEmpty(page.getRecords())) {
            // 获取所有商品店铺信息
            List<Integer> goodsShopIdList = page.getRecords().stream().map(GdsListQueryResultVO::getShopId).distinct().collect(Collectors.toList());
            // 查询登录用户已申请经销商成功的店铺id
            List<BaseDealerApplyInfoVO> dealerApplyInfoList = goodsCatMapper.queryDealerApplyListByShop(userInfo.getShopId(), goodsShopIdList);
                goodsShopIdList = dealerApplyInfoList.stream().map(BaseDealerApplyInfoVO::getSupplierShopId).distinct().collect(Collectors.toList());
            for (GdsListQueryResultVO goods : page.getRecords()) {
                if (null != goods.getPutawayId()) {
                    // 商品已经销
                    goods.setOperateType(4);
                } else {
                    // 商品无需申请经销商
                    if (null == goods.getSellCheck() || goods.getSellCheck().intValue() == 2) {
                        goods.setOperateType(null == goods.getSellDeliver() ? 1 : goods.getSellDeliver());
                    } else {
                        if (!goodsShopIdList.contains(goods.getShopId())) {
                            goods.setOperateType(CommonType.goodsOperateType.APPLY.getCode());
                        } else {
                            goods.setOperateType(goods.getSellDeliver());
                        }
                    }
                }
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult seckillCheckGoods(ManageSeckillBaseUpdateDTO param) {
        if (param != null ) {
            String seKillHourStr = "";
            if(null != param.getSeckillHour() && null != param.getSeckillStartDate()) {
                switch (param.getSeckillHour()) {
                    case 1:
                        seKillHourStr = "08:00:00";
                        break;
                    case 2:
                        seKillHourStr = "12:00:00";
                        break;
                    case 3:
                        seKillHourStr = "16:00:00";
                        break;
                    case 4:
                        seKillHourStr = "20:00:00";
                        break;
                    case 5:
                        seKillHourStr = "00:00:00";
                        break;
                    default:
                        seKillHourStr = "00:00:00";
                }
            }
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String seckillStartTime = simpleDateFormat2.format(param.getSeckillStartDate()) + " " + seKillHourStr;
            List<SeckillGoodsListDTO> seckillGoodsList = param.getSeckillGoodsList();
            if (seckillGoodsList != null && seckillGoodsList.size()>0) {
                for (SeckillGoodsListDTO goodsList : seckillGoodsList) {
                    //查看是否参加其他类型活动(integer不为null是没参加其他活动)
                    Integer integer = this.baseMapper.selectCommonIsXian(goodsList.getCommonId());
                    //查看参加同类型活动商品是否冲突(为null时没冲突)
                    List<AppSeckillGoodsVO> seckillGoodsResults = null;
                    if (param.getSeckillId() != null){
                        seckillGoodsResults =  this.baseMapper.selectSeckillGoodsId1(goodsList.getGoodsId(), seckillStartTime,param.getSeckillId());
                    }else {
                        seckillGoodsResults = this.baseMapper.selectSeckillGoodsId(goodsList.getGoodsId(), seckillStartTime);
                    }
                    if (integer == 0 || (seckillGoodsResults != null && seckillGoodsResults.size()>0)){
                        return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"同一活动时间段内，部分活动商品已参加了其他互斥的营销活动，请调整商品或活动时间");
                    }
                }
                return ResponseResult.success("无 互斥活动");
            }
        }
        return ResponseResult.success();

    }

    @Override
    public ResponseResult selecPlustGoodsByPage(Map<String, Object> map) {
        //查询平台最低会员折扣
        String memberdiscount = this.baseMapper.selectmemberdiscount();
        BigDecimal bigDecimal = new BigDecimal(memberdiscount);

        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if(userInfoVO == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("shopId",userInfoVO.getShopId());
        IPage<ManageGdsNameQueryVO> page=this.baseMapper.selectByGdsNameByPlus(new Query<ManageGdsNameQueryVO>().getPage(map),
                map);

        //查询最低折扣
        String mindiscount = mindiscount();

        for (ManageGdsNameQueryVO good : page.getRecords()) {
            List<VoucherMessageVO> voucherMes = this.baseMapper.selectVoucherMes(good.getCommonId());
            List<ManageGoodsBaseListVO> goodsBases =goodsBaseMapper.selectByGoodsList(good.getCommonId());
            good.setGoodsList(goodsBases);
            //查询最小库存和价格
            Map map1 = this.baseMapper.selectByGdsNamemin(good.getCommonId());
            good.setCommonStock(Integer.valueOf(String.valueOf(map1.get("goodsStock"))) );
            good.setCommonPrice(String.valueOf(map1.get("goodsPrice")));
            if (mindiscount != null){
                String goodsPrice = String.valueOf(map1.get("goodsPrice"));
                BigDecimal price = new BigDecimal(goodsPrice);
                BigDecimal discount = new BigDecimal(mindiscount);
                //价格 * 会员折扣 * (1 - plus折扣)
                price = price.multiply(bigDecimal).multiply(discount);
                price = price.setScale(2, BigDecimal.ROUND_HALF_UP);
                good.setDiscountPrice(String.valueOf(price));
            }

            if (CollectionUtils.isEmpty(voucherMes)) {
                voucherMes = Lists.newArrayList();
            }
            good.setVoucherMes(voucherMes);
            if(null == good.getSellEdit()){
                good.setSellEdit(1);
            }
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deletePlusGoods(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        if (userInfoStr == null || userInfoStr == ""){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("plusGoods",0);
        Integer integer = this.baseMapper.updatePlusGoods(map);
        if (integer > 0){
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult queryGiveawayList(ManjianzengzheListQueryDTO param) throws IllegalAccessException {

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions("", param.getToken());
        if (userPermissionsResult.getFlag()) {

            param.setShopId(userPermissionsResult.getShopId());
            Map data= ParseMapUtils.beanToMap(param);
            IPage<GoodsCommonEntity> page=this.baseMapper.queryGiveawayList(new Query<GoodsCommonEntity>().getPage(data),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult discountCheckGoods(DiscountBaseAddParamDTO param) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //预热时间
        if(null == param.getPreStartHour()){
            param.setPreStartHour(0);
        }
        Calendar cal = Calendar.getInstance();
        Date fdate = param.getDiscountStartTime();
        cal.setTime(fdate);
        cal.add(Calendar.HOUR,-param.getPreStartHour());
        fdate = cal.getTime();
        String format = sdf.format(fdate);
        List<DiscountGoodsListDTO> discountGoodsList = param.getDiscountGoodsList();
        if (discountGoodsList != null && discountGoodsList.size()>0) {
            for (DiscountGoodsListDTO goodsList : discountGoodsList) {
                //查看是否参加其他类型活动(integer不为null是没参加其他活动)
                Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsCommonEntity>()
                                 .eq(GoodsCommonEntity::getCommonId,goodsList.getCommonId())
                                .in(GoodsCommonEntity::getCommonIsXian,0,3));
                //查看参加同类型活动商品是否冲突(为null时没冲突)
                List<DiscountGoodsListVO> goodsListResults = null;
                if (param.getDiscountId() != null){
                    goodsListResults =
                            this.baseMapper.selectDiscountGoodsId1(goodsList.getGoodsId(), format,param.getDiscountId());
                }else {
                    goodsListResults =
                            this.baseMapper.selectDiscountGoodsId(goodsList.getGoodsId(), format);
                }
                if (integer == 0 || (goodsListResults != null && goodsListResults.size()>0)){

                    return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"同一活动时间段内，部分活动商品已参加了其他互斥的营销活动，请调整商品或活动时间");
                }
            }
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),"无互斥活动");
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),"无互斥活动");
    }

    @Override
    public ResponseResult queryGoodsListByPintuan(Map<String, Object> param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.get("token").toString());

        if (userPermissionsResult.getFlag()) {
            Integer shopId = Integer.valueOf(userPermissionsResult.getShopId());
            param.put("shopId",shopId);

            IPage<GoodsCommonEntity> page=this.baseMapper.selectPromotionGoodsList2(new Query<GoodsCommonEntity>().getPage(param),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult queryIsPriceUpdate(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());

            Map data= ParseMapUtils.beanToMap(param);
            IPage<ManageGdsNameQueryVO> page=this.baseMapper.queryIsPriceUpdate(new Query<ManageGdsNameQueryVO>().getPage(data),
                    param);


            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult queryWaitRelease(ManageGdsNameQueryDTO param) throws IllegalAccessException {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            Date commonSellTime = new Date();
            param.setCommonSellTime(commonSellTime);
            Map data= ParseMapUtils.beanToMap(param);
            IPage<GoodsCommonEntity> page=this.baseMapper.selectWaitRelease(new Query<GoodsCommonEntity>().getPage(data),
                    param);

            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult setGoodsOnline(ManageCommonIdsDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            // 商品上架
            this.baseMapper.updateOnline(param.getCommonIds());
            goodsBaseMapper.updateOnline(param.getCommonIds());
            //通过mq 更新es的商品数据
            Map<String,Object> map= new HashMap<>();
            List<Integer> list = new ArrayList<>();
            list = param.getCommonIds();
            map.put("commonIdS",list);
            // 1 是添加  2是删除
            map.put("type",1);
            MqSendUtils.mqSendGoods(map);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult checkGoodsBySpecId(Map<String, Object> param) {

        IPage<GoodsCommonEntity> page=this.baseMapper.selectGoodsBySpecId(new Query<GoodsCommonEntity>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));

    }

    @Override
    public ResponseResult deleteBySpecId(Map<String, Object> param) {
        Integer specValueId = Integer.valueOf(param.get("specValueId").toString());

        List<GoodsCommonEntity> specDeleteCommonList = this.baseMapper.selectBySpecValueId(specValueId);

        if (specValueId.equals(4)) {
            return ResponseResult.fail(0, "此规格不能删除");
        }
        goodsSpecValueMapper.deleteById(specValueId);
        if (CollectionUtils.isEmpty(specDeleteCommonList)) {
            return ResponseResult.fail();
        }

        // 商品下架
        goodsBaseMapper.update(null,new LambdaUpdateWrapper<GoodsBaseEntity>()
                       .set(GoodsBaseEntity::getGoodsIsShelves,2)
                        .eq(GoodsBaseEntity::getGoodsSpec,specValueId.toString()));
        for (GoodsCommonEntity specDeleteCommon : specDeleteCommonList) {
            // 根据commonId获取goodsId和规格

            List<ManageGdsBaseAddResultVO> gdsSpecs = goodsBaseMapper.selectByCommonId(specDeleteCommon.getCommonId());

            if (CollectionUtils.isEmpty(gdsSpecs)) {
                PlatFormGoodsStateDTO state = new PlatFormGoodsStateDTO();
                state.setCommonId(specDeleteCommon.getCommonId());
                state.setCommonState(0);
                goodsCommonMapper.updateGoodsState(state);
                continue;
            }

            // 更新goods_common中规格
            UpdateGdsSpecParamDTO updateGdsSpecParam = new UpdateGdsSpecParamDTO();
            updateGdsSpecParam.setCommonId(specDeleteCommon.getCommonId());
            // commonSpecValue
            List<CommonSpecValueDTO> commonSpecValues = Lists.newArrayList();
            Integer commonStock = 0;
            for (ManageGdsBaseAddResultVO gdsSpec : gdsSpecs) {
                CommonSpecValueDTO value = new CommonSpecValueDTO();
                value.setCommonId(specDeleteCommon.getCommonId());
                value.setGoodsId(gdsSpec.getGoodsId());
                value.setGoodsSpecId(Integer.parseInt(gdsSpec.getGoodsSpec()));
                value.setSpecNameId(Integer.parseInt(specDeleteCommon.getCommonSpecName()));
                commonStock = commonStock + gdsSpec.getGoodsStock();
                commonSpecValues.add(value);
            }
            updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));
            updateGdsSpecParam.setCommonStock(commonStock);
            updateGdsSpecParam.setGoodsId(gdsSpecs.get(0).getGoodsId().toString());
            goodsCommonMapper.updateGdsSpec(updateGdsSpecParam);
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult setGoodsOffline(ManageCommonIdsDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            Map<String,Object> map= new HashMap<>();
            List<Integer> list = new ArrayList<>();


            // 商品下架
            goodsCommonMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                             .set(GoodsCommonEntity::getCommonState,0)
                             .in(GoodsCommonEntity::getCommonId,param.getCommonIds()));
            goodsBaseMapper.update(null,new LambdaUpdateWrapper<GoodsBaseEntity>()
                            .set(GoodsBaseEntity::getGoodsIsShelves,2)
                            .eq(GoodsBaseEntity::getGoodsIsShelves,1)
                            .in(GoodsBaseEntity::getCommonId,param.getCommonIds()));
            List<Integer> commonIds = param.getCommonIds();
            for (Integer commonId : commonIds) {
                //判断当前是否是是供应商商品 如果是 下级商家对应的商品 并更新es
                List<Integer> dealerCommonIds = goodsCommonMapper.queryIsSupperGoods(commonId);
                if(null != dealerCommonIds && dealerCommonIds.size() >0 ){
                    //当前商品是供应商商品 所有商家商品下架 更新es
                    goodsCommonMapper.updateOffline(dealerCommonIds);
//					goodsBaseMapper.cancelDealerGoodsBase(dealerCommonIds);
                    list.addAll(dealerCommonIds);
                }
            }
            list.addAll(param.getCommonIds());
            //通过mq 更新es的商品数据
            map.put("commonIdS",list);
            // 1 是添加  2是删除
            map.put("type",2);
            MqSendUtils.mqSendGoods(map);
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    //计算最低折扣
    public String mindiscount(){
        //查询套餐表
        List<PlusThaliEntityVO> plusThaliEntities = this.baseMapper.selectthaliList();
        List returnList = new ArrayList<>();
        if (plusThaliEntities != null && plusThaliEntities.size() > 0){
            for (PlusThaliEntityVO plusThaliEntity : plusThaliEntities) {

                String thaliEquity = plusThaliEntity.getThaliEquity();
                String[] split = thaliEquity.split(",");
                List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                plusThaliEntity.setThaliEquityList(appIdList);

                List<PlusEquityEntityVO> selectplusequitys = this.baseMapper.selectplusequitys(appIdList);
                if (selectplusequitys != null && selectplusequitys.size() > 0){
                    for (PlusEquityEntityVO selectplusequity : selectplusequitys) {
                        if (selectplusequity.getEquityType() == 1){
                            String equityValue = selectplusequity.getEquityValue();
                            BigDecimal bigDecimal1 = new BigDecimal(equityValue);
                            returnList.add(bigDecimal1);
                        }
                    }
                }
            }
        }
        if (returnList != null && returnList.size() > 0){
            return String.valueOf(Collections.min(returnList)) ;
        }
        return null;
    }

    @Override
    public ResponseResult updatePlusGoods(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        if (userInfoStr == null || userInfoStr == ""){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("plusGoods",1);
        Integer integer = this.baseMapper.updatePlusGoods(map);
        if (integer > 0){
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
    }


    @Override
    public ResponseResult checkGoodsName(CheckNameQueryParamDTO param) {
        // 2重复3不重复
        Integer flag = 2;
        if (null != param.getCommonId()) {
            String commonName = this.baseMapper.queryCommonName(param.getCommonId());
            if (null != commonName && commonName.equals(param.getCheckName())) {
                flag = 3;
                return ResponseResult.success(flag);
            }
        }
        Integer checkName = this.baseMapper.selectCommonName(param);
        if (null == checkName) {
            flag = 3;
        }
        return ResponseResult.success(flag);
    }

    @Override
    public ResponseResult livequeryByGoodsName(ManageGdsNameQueryDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        if (null == param.getSupplyShopId()) {
            param.setShopId(userPermissionsResult.getShopId());
        }
        List<Integer> integers = this.baseMapper.queryLiveCommons2(userPermissionsResult.getShopId());
        // 查询出售中的商品
        Page<ManageGdsNameQueryVO> page  = new Page<>(param.getPage(),param.getLimit());
        IPage<ManageGdsNameQueryVO> goods = this.baseMapper.selectByGdsName2(page,param,integers);

        for (ManageGdsNameQueryVO good : goods.getRecords()) {
            List<VoucherMessageVO> voucherMes = this.baseMapper.selectVoucherMes(good.getCommonId());
            if (CollectionUtils.isEmpty(voucherMes)) {
                voucherMes = Lists.newArrayList();
            }
            good.setVoucherMes(voucherMes);
        }
        return ResponseResult.success(PageUtils.getPage(goods));
    }

    /**
     * 商品分类授权校验
     * @param passShopCatList
     * @param goodsCatList
     * @return
     */
    private Boolean queryGoodsCat(List<ManageGoodsSelfCatVO> passShopCatList, List<ShopGoodsCatVO> goodsCatList){
        List<Integer> passCatIdList = passShopCatList.stream().map(ManageGoodsSelfCatVO::getShopGoodsCatId).collect(Collectors.toList());
        List<Integer> goodsCatIdList = goodsCatList.stream().map(ShopGoodsCatVO::getShopGoodsCatId).collect(Collectors.toList());
        // 校验商品的分类id是否有申请记录
        List<Integer> passCatList = goodsCatIdList.stream().filter(item -> passCatIdList.contains(item)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(passCatList)){
            // 校验商品的父类id是否有申请记录
            List<Integer> goodsParentCatIdList = goodsCatList.stream().map(ShopGoodsCatVO::getParentId).distinct().collect(Collectors.toList());
            passCatList = goodsParentCatIdList.stream().filter(item -> passCatIdList.contains(item)).collect(Collectors.toList());
        }
        if(!CollectionUtils.isEmpty(passCatList)){
            return true;
        }
        return false;
    }

    @Override
    public ResponseResult shopListQueryByShopFilter(ListPageQueryParamDTO param) {
        Integer selectshoptype = 0;
        if (param.getShopId() != null) {
            selectshoptype = this.baseMapper.selectshoptype(param.getShopId());
        }
        //查询当前分类等级
        if (selectshoptype != 3) {
            if(null != param.getCatId()) {
                //普通店铺
                WebCatMenuVO webCatMenu = goodsCatMapper.queryByCatId(param.getCatId());
                List<Integer> catIdList = new ArrayList<>();
                if (webCatMenu != null) {
                    //点击一级分类
                    if (webCatMenu.getCatLevel() != null && webCatMenu.getCatLevel() == 1) {
                        List<WebCatMenuVO> nextCatIds = goodsCatMapper.selectByCatParentId2(webCatMenu.getCatId());
                        if (nextCatIds != null && !nextCatIds.isEmpty()) {
                            for (WebCatMenuVO nextCatId : nextCatIds) {
                                List<WebCatMenuVO> nextCatIds1 = goodsCatMapper.selectByCatParentId2(nextCatId.getCatId());
                                if (nextCatIds1 != null && !nextCatIds1.isEmpty()) {
                                    List<Integer> catIds = catIds(nextCatIds1);
                                    catIdList.addAll(catIds);
                                }
                            }
                            param.setCatId(null);
                            param.setCatIds(catIdList);
                        }
                    } else if (webCatMenu.getCatLevel() != null && webCatMenu.getCatLevel() == 2) {
                        //点击二级分类
                        List<WebCatMenuVO> nextCatIds1 = goodsCatMapper.selectByCatParentId2(webCatMenu.getCatId());
                        if (nextCatIds1 != null && !nextCatIds1.isEmpty()) {
                            List<Integer> catIds = catIds(nextCatIds1);
                            param.setCatId(null);
                            param.setCatIds(catIds);
                        }
                    }
                }
            }
            Map data = null;
            try {
                data = ParseMapUtils.beanToMap(param);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            IPage<GdsListQueryResultVO> page = this.baseMapper.selectByFilter(new Query<GdsListQueryResultVO>().getPage(data),param);
            List<GdsListQueryResultVO> records = page.getRecords();
            for (GdsListQueryResultVO gdsListQueryResult : records) {
                gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));
                if (gdsListQueryResult.getGoodsIdOne() == 1) {
                    List<Integer> goodsIds = goodsBaseMapper.selectGoodsId(gdsListQueryResult.getCommonId());
                    if (!CollectionUtils.isEmpty(goodsIds)) {
                        gdsListQueryResult.setGoodsIdOne(goodsIds.get(0));
                    }
                }

                gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));

                Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
                // 活动
                ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(),
                        gdsListQueryResult.getCommonId(), commonIsXian);

                if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                    gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                    gdsListQueryResult.setActivityGoodsDetailDTO(activityGoodsDetail);
                    gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                    if (activityGoodsDetail.getActivityStatus() == 5) {
                        gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                    }
                } else {
                    gdsListQueryResult.setActivityStatus(0);
                    gdsListQueryResult.setActivityGoodsDetailDTO(new ActivityGoodsDetailDTO());
                    gdsListQueryResult.setCommonIsXian(0);
                }
            }
            page.setRecords(records);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            //品牌店铺
            if (param.getCatId() != null) {
                param.setCatIdstring(String.valueOf(param.getCatId()));
            }
            Map data = null;
            try {
                data = ParseMapUtils.beanToMap(param);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            IPage<GdsListQueryResultVO> page = this.baseMapper.selectShopByFilter(new Query<GdsListQueryResultVO>().getPage(data),param);
            List<GdsListQueryResultVO> records = page.getRecords();
            for (GdsListQueryResultVO gdsListQueryResult : records) {
                gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));
                if (gdsListQueryResult.getGoodsIdOne() == 1) {
                    List<Integer> goodsIds = goodsBaseMapper.selectGoodsId(gdsListQueryResult.getCommonId());
                    if (!CollectionUtils.isEmpty(goodsIds)) {
                        gdsListQueryResult.setGoodsIdOne(goodsIds.get(0));
                    }
                }

                gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));

                Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
                // 活动
                ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(),
                        gdsListQueryResult.getCommonId(), commonIsXian);

                if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                    gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                    gdsListQueryResult.setActivityGoodsDetailDTO(activityGoodsDetail);
                    gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                    if (activityGoodsDetail.getActivityStatus() == 5) {
                        gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                    }
                } else {
                    gdsListQueryResult.setActivityStatus(0);
                    gdsListQueryResult.setActivityGoodsDetailDTO(new ActivityGoodsDetailDTO());
                    gdsListQueryResult.setCommonIsXian(0);
                }
            }
            page.setRecords(records);
            return ResponseResult.success(PageUtils.getPage(page));
        }

    }

    @Override
    public ResponseResult queryGoods(Map<String, Object> param) {
        IPage<GoodsInfoDTO> goodsInfo=this.baseMapper.queryGoodsInfo2(new Query<GoodsInfoDTO>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(goodsInfo));
    }

    @Override
    public ResponseResult queryByFilter(ShopIndexQueryParamDTO param) throws IllegalAccessException {
        Page<ListQueryResultVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<ListQueryResultVO> gdsList = this.baseMapper.selectByShopFilter(page, param);
        for (ListQueryResultVO gdsListQueryResult : gdsList.getRecords()) {
            gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));

            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(),
                    gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if(activityGoodsDetail.getActivityStatus() == 5){
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(0);
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(0);
            }
        }
        return ResponseResult.success(gdsList);
    }

    @Override
    public ResponseResult queryShopIndexquery(ShopIndexQueryParamDTO param) throws IllegalAccessException {
        // 根据shopId查询所有商品
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ListQueryResultVO> gdsList=this.baseMapper.selectByShopIndex2(new Query<ListQueryResultVO>().getPage(data),
                param);
        for (ListQueryResultVO gdsListQueryResult : gdsList.getRecords()) {
            gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));

            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(),
                    gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if(activityGoodsDetail.getActivityStatus() == 5){
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(0);
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(0);
            }

        }
        // 查询首页信息
        ShopIndexVO shopIndex = this.baseMapper.selectByParam(param.getShopId());
        if(shopIndex == null){
            return ResponseResult.fail(2,"无店铺信息");
        }
        shopIndex.setIsEnshrine(1);
        Integer shopSumNum = goodsCommonMapper.selectShopSum(param.getShopId());

        // 处理轮播信息
        dealShopSlide(shopIndex);

        String configValue = null;

        if (shopIndex.getShopImage() == null || shopIndex.getShopImage().equals("") || shopIndex.getShopLogo() == null
                || shopIndex.getShopLogo().equals("") || shopIndex.getWapShopLogo() == null
                || shopIndex.getWapShopLogo().equals("")) {
            configValue = baseServiceClient.selectConfigValueFeign("shop_default_config");
            ShopConfigDefaultValueVO shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueVO.class);

            if (shopIndex.getShopImage() == null || shopIndex.getShopImage().equals("")) {
                shopIndex.setShopImage(shopConfig.getShopImage());
            }
            if (shopIndex.getShopLogo() == null || shopIndex.getShopLogo().equals("")) {
                shopIndex.setShopLogo(shopConfig.getShopLogo());
            }
            if ((shopIndex.getWapShopLogo() == null || shopIndex.getWapShopLogo().equals(""))
                    && shopIndex.getShopLogo() != null) {
                shopIndex.setWapShopLogo(shopConfig.getShopLogo());
            }
            if (shopIndex.getWapShopLogo() == null || shopIndex.getWapShopLogo().equals("")) {
                shopIndex.setWapShopLogo(shopConfig.getWapShopLogo());
            }

            if (shopIndex.getShopSlide() == null || shopIndex.getShopSlide().equals("")) {
                shopIndex.setShopSlide(shopConfig.getShopSlide());
            }
        }
        shopIndex.setShopSumNum(shopSumNum);
        shopIndex.setGdsList(gdsList.getRecords());
        return ResponseResult.success(shopIndex);
    }

    @Override
    public ResponseResult zipLocalDiskImage(byte[] sourceZipFileBytes, List<String> commonList) throws IOException {
        // 变量定义.
        String zipEntryName = null;
        ZipEntry singleZipEntry = null;
        ZipInputStream sourceZipZis = null;
        BufferedInputStream sourceZipBis = null;
        ByteArrayInputStream sourceZipBais = null;
        Map<String, byte[]> targetFilesFolderMap = null;

        try {
            // 解压变量初始化.
            targetFilesFolderMap = new HashMap<String, byte[]>();
            sourceZipBais = new ByteArrayInputStream(sourceZipFileBytes);
            sourceZipBis = new BufferedInputStream(sourceZipBais);
            sourceZipZis = new ZipInputStream(sourceZipBis, Charset.forName("GBK"));
            // 条目解压缩至Map中.
            while ((singleZipEntry = sourceZipZis.getNextEntry()) != null) {
                zipEntryName = singleZipEntry.getName();
                String var = zipEntryName.substring(zipEntryName.indexOf("/"),zipEntryName.length());
                if (!"/".equals(var)){
                    targetFilesFolderMap.put(zipEntryName, IOUtils.toByteArray(sourceZipZis));
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (null != sourceZipZis){
                sourceZipZis.close();
            }
            if (null != sourceZipBis){
                sourceZipBis.close();
            }
            if (null != sourceZipBais){
                sourceZipBais.close();
            }
        }
        //OSS图片上传
        return ResponseResult.success(importUploadOSS(targetFilesFolderMap,commonList));
    }

    @Override
    public ResponseResult insertGoodsBatch(MultipartFile file, String token, Integer transportAreaId, Integer transportTemplate) throws Exception {
        String fileName = file.getOriginalFilename();
        int lastIndex = fileName.lastIndexOf(".");
        // 获取上传文件的扩展名
        String extensionName = fileName.substring(lastIndex, fileName.length());
        // 判断需要用xls，还是xlsx
        boolean isExcels = true;
        if (extensionName.equals(".xls")) {
            isExcels = false;
        }
        // 解析excel数据
        Map<String, Object> datas = readExcel(file.getInputStream(), isExcels);
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (null != datas) {
            GoodsBatchCommonVO param = new GoodsBatchCommonVO();
            param.setTransportAreaId(transportAreaId);
            param.setTransportTemplate(transportTemplate);
            param.setToken(token);
            Map<String, Object> result = importExcelData(datas, param);
            if (null == result) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            // 说明数据有错误
            if (null != result && !result.isEmpty() && null != result.get("errorMsg")) {
                Map errorMap = (Map) result.get("errorMsg");
                if (!errorMap.isEmpty()) {
                    UUID uuid = UUID.randomUUID();
                    RedisUtil.set(uuid.toString(), JSON.toJSONString(result), 60 * 60 * 24);
                    returnMap.put("errorMsg", uuid.toString());
                }
            }
            if (null != result && !result.isEmpty() && null != result.get("commonIds")) {
                returnMap.put("success", result.get("commonIds"));
            }
            returnMap.put("isUploadUnzip", datas.get("isUploadUnzip"));

        } else {
            return ResponseResult.fail(0, "解析excel 数据错误");
        }
        return ResponseResult.success(returnMap);
    }




    @Override
    public Map<String, Object> importExcelData(Map<String, Object> dataParam, GoodsBatchCommonVO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());
        if (null != userPermissionsResult) {
            Map<String, Object> result = new HashMap<>();
            List<ImportGoodsDataBeanVO> importData = new ArrayList<>();
            List<Integer> commonIds = new ArrayList<Integer>();
            Map<String, ImportGoodsDataBeanVO> importGoodsDataBeans = (Map<String, ImportGoodsDataBeanVO>) dataParam
                    .get("goodsCommonMap");
            ImportGoodsDataBeanVO record = null;
            Map<String, Object> seccussMap = new HashMap<String, Object>();
            for (String key : importGoodsDataBeans.keySet()) {
                // 取处spu
                record = importGoodsDataBeans.get(key);
                if (null != record.getGdbMerchantGoodsCommon()) {
                    Integer commonId = saveData(record, param);
                    if (null != commonId) {
                        commonIds.add(commonId);
                    } else {
                        importData.add(record);
                    }
                }
            }
            result.put("commonIds", commonIds);
            result.put("errorMsg", dataParam.get("errorMsg"));
            if (!importData.isEmpty()) {
                result.put("importData", importData);
            }
            return result;
        }
        return null;
    }

    @Override
    public ResponseResult updateSupperGoodsStart(Map<String, Object> param) {
        UserInfoVO userinfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if(null == userinfo){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        List<Integer> commonIds = (List<Integer>) param.get("commonIds");
        if(null != commonIds && commonIds.size() > 0){
            for (Integer commonId : commonIds) {
                // 查询代发商品 所同步的供应商商品是否在售
                Integer supplierGoodsStart = goodsCommonMapper.querySupplierGoodsStart(commonId);
                if(0 < supplierGoodsStart){
                    // 商品 不在售 所有经销商品不能 上架
                    return ResponseResult.success(2,"有商品在供应商端未在售，商品不能上架!");
                }
            }
        }
        this.baseMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                        .set(GoodsCommonEntity::getCommonState,CommonType.commonStatus.YES.getCode())
                        .in(GoodsCommonEntity::getCommonId,commonIds));
        goodsCommonMapper.updateSupperGoodsStart(commonIds);
        Map<String,Object> map= new HashMap<>();
        map.put("commonIdS",commonIds);
        // 1 是添加  2是删除
        map.put("type",1);
        MqSendUtils.mqSendGoods(map);
        return ResponseResult.success("上架成功！");
    }

    @Override
    public void updateGiveawayStock(List<Integer> commonIdList) {
        for (Integer commonId : commonIdList) {
            GoodsCommonEntity entity = this.baseMapper.selectById(commonId);
            List<GoodsBaseEntity> list = goodsBaseMapper.selectList(new LambdaQueryWrapper<GoodsBaseEntity>()
                    .eq(GoodsBaseEntity::getCommonId, commonId));
            GoodsBaseEntity baseEntity = new GoodsBaseEntity();
            for (GoodsBaseEntity base : list) {
                if (base.getGoodsStock() > 0) {
                    baseEntity = base;
                    break;
                }
            }
            int num = 1;
            Integer commonStock = entity.getCommonStock() > 0 ? entity.getCommonStock() : 0;
            Integer goodsStock = baseEntity.getGoodsStock() > 0 ? baseEntity.getGoodsStock() : 0;
            if (baseEntity.getGoodsStock() > 0) {
                if ((entity.getCommonStock() - num) >= 0) {
                    commonStock = entity.getCommonStock() - num;
                }
                if ((baseEntity.getGoodsStock() - num) >= 0) {
                    goodsStock = baseEntity.getGoodsStock() - num;
                }
            }
            // 更新spu库存
            this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .eq(GoodsCommonEntity::getCommonId, entity.getCommonId())
                    .set(GoodsCommonEntity::getCommonSalenum, entity.getCommonSalenum() + num)
                    .set(GoodsCommonEntity::getCommonStock, commonStock));
            // 更新sku库存
            goodsBaseMapper.update(baseEntity, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .eq(GoodsBaseEntity::getGoodsId, baseEntity.getGoodsId())
                    .set(GoodsBaseEntity::getGoodsSalenum, baseEntity.getGoodsSalenum() + num)
                    .set(GoodsBaseEntity::getGoodsStock, goodsStock));
        }
    }

    /**
     * 查询待发布的商品
     *
     * @param param
     * @return
     */
    @Override
    public ResponseResult queryToBeReleased(ManageGdsNameQueryParamDTO param) {
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(param.getToken());
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        UserInfoVO ui = JSON.parseObject(JSON.toJSONString(rr.getData()), UserInfoVO.class);
        param.setShopId(ui.getShopId());
        //分页查询等待审核的商品
        Page<ManageGdsNameVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<ManageGdsNameVO> goods = this.baseMapper.queryToBeReleased(page, param);
        return ResponseResult.success(PageUtils.getPage(goods));
    }
    /**
     * 定时发布商品--立即发布
     *
     * @param param
     * @return
     */
    @Override
    public ResponseResult fixedTimeGoodsPublishNow(ManageCommonIdsDTO param) {
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(param.getToken());
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        Boolean commonFlag = false;
        Boolean goodsFlag = false;
        for (Integer commonId : param.getCommonIds()) {
            // 更改商品状态
            commonFlag = this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .set(GoodsCommonEntity::getCommonState, CommonType.commonStatus.YES.getCode())
                    .eq(GoodsCommonEntity::getCommonId, commonId)) > 0;
            goodsFlag = goodsBaseMapper.update(null, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .set(GoodsBaseEntity::getGoodsIsShelves, CommonType.goodsIsShelves.GOODS_ON_THE_SHELF.getCode())
                    .eq(GoodsBaseEntity::getCommonId, commonId)) > 0;
        }

        if (commonFlag && goodsFlag) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    /**
     * 放入仓库商品--立即审核
     *
     * @param param
     * @return
     */
    @Override
    public ResponseResult putIntoWarehouseGoodsReviewingNow(ManageCommonIdsDTO param) {
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(param.getToken());
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        Boolean commonFlag = false;
        Boolean goodsFlag = false;
        for (Integer commonId : param.getCommonIds()) {
            // 更改商品状态
            commonFlag = this.baseMapper.update(null, new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .set(GoodsCommonEntity::getCommonState, CommonType.commonStatus.YES.getCode())
                    .set(GoodsCommonEntity::getCommonVerify, CommonType.productReview.UNDER_REVIEW.getCode())
                    .eq(GoodsCommonEntity::getCommonId, commonId)) > 0;
            goodsFlag = goodsBaseMapper.update(null, new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .set(GoodsBaseEntity::getGoodsIsShelves, CommonType.goodsIsShelves.GOODS_ON_THE_SHELF.getCode())
                    .eq(GoodsBaseEntity::getCommonId, commonId)) > 0;
        }
        if (commonFlag && goodsFlag) {
            return ResponseResult.success();
        }
        return null;
    }

    @Transactional
    public Integer saveData(ImportGoodsDataBeanVO record, GoodsBatchCommonVO param) {
        Integer commonId = null;
        // 导入spu
        GdbMerchantGoodsCommonVO recordGoodsCommon = record.getGdbMerchantGoodsCommon();
        recordGoodsCommon.setTransportAreaId(param.getTransportAreaId());
        recordGoodsCommon.setTransportTemplate(param.getTransportTemplate());
        recordGoodsCommon.setCommonProperty("[]");
        this.baseMapper.importDataGoodsCommon(recordGoodsCommon);
        commonId = recordGoodsCommon.getCommonId();
        GoodsCommonEntity common = this.baseMapper.selectById(commonId);

        // 插入商品主图
        List<GdbMerchantGoodsImagesVO> imageRecords = record.getGoodsImages();
        if(null != imageRecords && !imageRecords.isEmpty()) {
            for(GdbMerchantGoodsImagesVO imageRecord : imageRecords) {
                // 文件名不为空 且 图片是链接
                if(StringUtils.isNotEmpty(imageRecord.getImagesImage()) && ExcelsUtil.isHttpUrl(imageRecord.getImagesImage())) {
                    imageRecord.setCommonId(commonId);
                    imageRecord.setShopId(recordGoodsCommon.getShopId());
                    goodsImagesMapper.insertSelective(imageRecord);
                }
            }
        }
        //处理http商详链接
        String commonDetailImage = record.getImageName();
        if(StringUtils.isNotEmpty(commonDetailImage)) {
            String[] commonDetailImages = commonDetailImage.split("\\;");
            StringBuffer sb = new StringBuffer();
            for(String tempImagePath : commonDetailImages) {
                if(StringUtils.isNotEmpty(tempImagePath)) {
                    String temp = "<p><img class=\"wscnph\" src=\"".concat(tempImagePath).concat("\" />");
                    sb.append(temp);
                }
            }
            GoodsCommonDetailEntity entity=new GoodsCommonDetailEntity();
            entity.setCommonId(commonId);
            entity.setCommonBody(sb.toString());
            goodsCommonDetailMapper.insert(entity);
        }
        Integer commonStock = 0;
        List<GdbMerchantGoodsBaseVO> recordGoodsBases = record.getGdbMerchantGoodsBases();
        if (null != recordGoodsBases && !recordGoodsBases.isEmpty()) {
            for (GdbMerchantGoodsBaseVO base : recordGoodsBases) {
                base.setCommonId(commonId);
                base.setShopId(Integer.valueOf(recordGoodsCommon.getShopId()));
                base.setShopName(recordGoodsCommon.getShopName());
                base.setIsUse(1);
                base.setCatId(recordGoodsCommon.getCatId());
//				base.setGoodsName(common.getCommonName());
                base.setGoodsAlarm(100);
                base.setGoodsMaxSale(100);
                base.setGoodsImage(recordGoodsCommon.getCommonImage());
                commonStock += base.getGoodsStock();
                goodsBaseMapper.insertSelective(base);
            }
        }
        if(null != recordGoodsBases && recordGoodsBases.size()>0  ){
            this.baseMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                           .set(GoodsCommonEntity::getCommonStock,commonStock)
                           .set(GoodsCommonEntity::getGoodsId,recordGoodsBases.get(0).getGoodsId())
                           .eq(GoodsCommonEntity::getCommonId,commonId));
        }
        return commonId;
    }

    public Map<String, Object> readExcel(InputStream is, boolean isExcels) throws Exception {
        Workbook wookbook = null;
        if (isExcels) {
            wookbook = new XSSFWorkbook(is);
        } else {
            wookbook = new HSSFWorkbook(is);
        }
        return analysisExcel(wookbook);
    }

    /**
     * wookbook 直接解析成数据
     *
     * @param wookbook
     * @return
     */
    private Map<String, Object> analysisExcel(Workbook wookbook) {
        if (null != wookbook) {
            boolean flag = false;
            Map<String, Object> resultMap = new HashMap<>();
            // 将goodscommon的数据存储
            Map<String, ImportGoodsDataBeanVO> goodsCommonMap = new HashMap<String, ImportGoodsDataBeanVO>();
            Sheet sheet = wookbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            Map<Integer, List<String>> errorMsg = new HashMap<Integer, List<String>>();
            // 相同编码 对应的行号
            Map<String, List<Integer>> codeNumberRow = new HashMap<>();
            // 用于记录 不相同的规格的 编码，最后统一删除spu
            List<String> errorSpec = new ArrayList<String>();

            logger.info("开始检查主图在本次上传的唯一性");
            List<String> errorMainImages = ExcelsUtil.checkMainImages(sheet);
            logger.info("结束检查主图在本次上传的唯一性");
            logger.info("开始校验同一spu 的shop id 是否相同");
            List<String> errorShopIds = ExcelsUtil.checkShopId(sheet);
            logger.info("结束校验同一spu 的shop id 是否相同");
            logger.info("开始校验同一spu 的规格类型 是否相同");
            List<String> errorSpecName = ExcelsUtil.checkSpec(sheet);
            logger.info("结束校验同一spu 的规格类型 是否相同");

            logger.info("开始检查数据的合法");

            for (int i = 1; i < rows; i++) {
                logger.info("begin analys Excel row number =" + i);
                Row row = sheet.getRow(i);
                if (null == row || row.getPhysicalNumberOfCells() == 0) {
                    continue;
                }

                Map<String, String> importMap = new HashMap<String, String>();
                // 商品名称
                String goodsName = "";
                // 三级分类对应的类型
                Integer threeTypeId = null;
                // 默认每一行都有错误，如果没有错误 errorMsg 长度为0
                List<String> errorRow = new ArrayList<>();
                if (row != null) {
                    // 取值编码 存储到 goodsCommonMap里面
                    Cell codeNumberCell = row.getCell(0);
                    String codeNumber = ExcelsUtil.getValue(codeNumberCell);
                    // 编码为空 退出当前循环
                    if (StringUtils.isEmpty(codeNumber)) {
                        logger.info("编码为空");
                        continue;
                    }

                    List<Integer> codeNumberRows = null;
                    if (codeNumberRow.isEmpty() || null == codeNumberRow.get(codeNumber)
                            || codeNumberRow.get(codeNumber).isEmpty()) {
                        codeNumberRows = new ArrayList<Integer>();
                    } else {
                        codeNumberRows = codeNumberRow.get(codeNumber);
                    }
                    codeNumberRows.add(i);
                    codeNumberRow.put(codeNumber, codeNumberRows);
                    // 第一列的编码作为key值，key值不存在，保存
                    if (!goodsCommonMap.containsKey(codeNumber)) {
                        goodsCommonMap.put(codeNumber, new ImportGoodsDataBeanVO());
                    }
                    ImportGoodsDataBeanVO importGoodsData = goodsCommonMap.get(codeNumber);

                    // 组装spu
                    GdbMerchantGoodsCommonVO commonRecord = new GdbMerchantGoodsCommonVO();
                    // shopid
                    Cell shopIdCell = row.getCell(1);
                    String shopIdS = ExcelsUtil.getValue(shopIdCell);
                    if (StringUtils.isNotEmpty(shopIdS)) {
                        if (MathUtil.checkNumber(shopIdS) && shopIdS.indexOf(".") < 0) {
                            String shopName = this.baseMapper.selectShopName(Integer.parseInt(shopIdS));
                            if(StringUtils.isNotEmpty(shopName)) {
                                commonRecord.setShopId(shopIdS);
                                commonRecord.setShopName(shopName);
                            } else {
                                errorRow.add("供应商ID;供应商ID不存在");
                            }
                        } else {
                            errorRow.add("供应商ID;供应商ID格式不正确");
                        }
                    } else {
                        errorRow.add("供应商ID;供应商ID不能为空");
                    }
                    if (!errorShopIds.isEmpty() && errorShopIds.contains(shopIdS)) {
                        errorRow.add("供应商ID;相同编码但供应商ID不相同");
                    }

                    // 商品名称
                    Cell goodsNameCell = row.getCell(2);
                    goodsName = ExcelsUtil.getValue(goodsNameCell);
                    if (StringUtils.isNotEmpty(goodsName)) {
                        if (goodsName.length() <= 300) {
                            commonRecord.setCommonName(goodsName);
                        } else {
                            errorRow.add("商品名称;商品名称长度不能超过300个字符");
                            goodsName = "";
                        }
                    } else {
                        errorRow.add("商品名称;商品名称不能为空");
                    }

                    // 解析三级类目
                    Cell threeCatIdCell = row.getCell(5);
                    String threeCatId = ExcelsUtil.getValue(threeCatIdCell);
                    Integer sendCatId = null;
                    String catName = "";
                    Map<String, Object> catMap = new HashMap<>();
                    if (StringUtils.isNotEmpty(threeCatId) && MathUtil.checkNumber(threeCatId)) {
                        catMap = getCatName(Integer.parseInt(threeCatId));
                        if (null != catMap.get("catName")) {
                            commonRecord.setCatId(Integer.parseInt(threeCatId));
                            commonRecord.setCatName((String) catMap.get("catName"));
                        } else {
                            // 三级类目有错误的
                            errorRow.add("三级类目;三级类目有误");
                        }
                        if (null != catMap.get("sendCatId")) {
                            sendCatId = (Integer) catMap.get("sendCatId");
                        }
                    } else {
                        errorRow.add("三级类目;三级类目不能为空");
                    }
                    List<ManageSpecNameVO> manageSpecNames = new ArrayList<>();
                    // 根据商品三级分类查询是否有公用属性，false 没有
                    boolean isCommonFlag = false;
                    if (!catMap.isEmpty() && null != catMap.get("threedCat")) {
                        GoodsCatEntity threedCat = (GoodsCatEntity) catMap.get("threedCat");
                        if (null != threedCat.getTypeId() && threedCat.getTypeId() != -1) {
                            threeTypeId = threedCat.getTypeId();
                            manageSpecNames = goodsSpecMapper.selectByTypeId(threedCat.getTypeId());
                        }
                        if (!manageSpecNames.isEmpty()) {
                            isCommonFlag = true;
                        }
                    }
                    if (null != threeTypeId) {
                        commonRecord.setTypeId(threeTypeId);
                    }
                    // TODO 组装规格属性
                    if (!errorSpecName.isEmpty() && errorSpecName.contains(codeNumber)) {
                        errorRow.add("规格类型;编码为" + codeNumber + " 的规格类型不相同");
                    }
                    Cell specParamCell = row.getCell(13);
                    String specParamStr = ExcelsUtil.getValue(specParamCell);
                    if (StringUtils.isNotEmpty(specParamStr)) {
                        String[] specParams = null;
                        if (specParamStr.indexOf("+") >= 0) {
                            specParams = specParamStr.split("\\+");
                        } else {
                            specParams = new String[1];
                            specParams[0] = specParamStr;
                        }
                        // 开始循环获取属性
                        int sort = 1;
                        List<SpecParamJsonBeanVO> specParamJsonBeans = new ArrayList<>();
                        for (String specParam : specParams) {
                            // 是否是公有属性
                            boolean isCommon = false;
                            SpecParamJsonBeanVO jsonBean = new SpecParamJsonBeanVO();
                            jsonBean.setParamName(specParam);
                            jsonBean.setSort(sort);
                            Integer refSpecId = null;
                            if (isCommonFlag) {
                                for (ManageSpecNameVO manageSpecName : manageSpecNames) {
                                    if (manageSpecName.getSpecName().equals(specParam)) {
                                        refSpecId = manageSpecName.getSpecId();
                                        isCommon = true;
                                        break;
                                    }
                                }
                                jsonBean.setIsCommon(isCommon);
                                jsonBean.setRefSpecId(refSpecId);
                            }
                            specParamJsonBeans.add(jsonBean);
                            sort++;
                        }
                        if (specParams.length > 3) {
                            errorRow.add("规格类型;规格类型不能超过3个");
                        }
                        if (!specParamJsonBeans.isEmpty()) {
                            commonRecord.setSpecParam(JSON.toJSONString(specParamJsonBeans));
                        }

                        // 处理spu成本价格
                        Cell commonCostCell = row.getCell(9);
                        String commonCostStr = ExcelsUtil.getValue(commonCostCell);
                        if (StringUtils.isNotEmpty(commonCostStr)) {
                            if (MathUtil.checkNumber(commonCostStr)) {
                                BigDecimal commonPrice = new BigDecimal(commonCostStr);
                                commonRecord.setCommonCostPrice(commonPrice);
                            } else {
                                errorRow.add("成本价（供货价）;成本价（供货价）格式不正确");
                            }
                        } else {
                            errorRow.add("成本价（供货价）;成本价（供货价）不能为空");
                        }
                        // 处理spu商品价
                        Cell commonPriceCell = row.getCell(10);
                        String commonPriceStr = ExcelsUtil.getValue(commonPriceCell);
                        if (StringUtils.isNotEmpty(commonPriceStr)) {
                            if (MathUtil.checkNumber(commonPriceStr)) {
                                BigDecimal commonPrice = new BigDecimal(commonPriceStr);
                                commonRecord.setCommonPrice(commonPrice);
                            } else {
                                errorRow.add("商品价 格式不正确");
                            }
                        } else {
                            errorRow.add("商品价 不能为空");
                        }
                        // 处理spu市场价
                        Cell commonMarketPriceCell = row.getCell(11);
                        String commonMarketPriceCellStr = ExcelsUtil.getValue(commonMarketPriceCell);
                        if (StringUtils.isNotEmpty(commonMarketPriceCellStr)) {
                            if (MathUtil.checkNumber(commonMarketPriceCellStr)) {
                                BigDecimal commonPrice = new BigDecimal(commonMarketPriceCellStr);
                                commonRecord.setCommonMarketPrice(commonPrice);
                            } else {
                                errorRow.add("市场价 格式不正确");
                            }
                        } else {
                            errorRow.add("市场价 不能为空");
                        }
                        //品牌id
                        Cell commonDetailCel16 = row.getCell(27);
                        String brandId = ExcelsUtil.getValue(commonDetailCel16);
                        if (StringUtils.isNotEmpty(brandId)) {
                            if (MathUtil.checkNumber(brandId)) {
                                commonRecord.setBrandId(Integer.parseInt(brandId));
                            }else{
                                commonRecord.setBrandId(0);
                            }
                        }else{
                            commonRecord.setBrandId(0);
                        }


                        if (!errorMainImages.isEmpty() && errorMainImages.contains(codeNumber)) {
                            errorRow.add("商品图片1;已经存在");
                        }

                        if (!errorMainImages.isEmpty() && errorMainImages.contains(codeNumber)) {
                            errorRow.add("商品图片1;已经存在");
                        }

                        // 处理spu商品图片
                        Cell goodsImagesCell1 = row.getCell(17);
                        if(null != goodsImagesCell1 && !ExcelsUtil.isHttpUrl(goodsImagesCell1)) {
                            importMap.put("1", ExcelsUtil.getValue(goodsImagesCell1));
                        }
                        Cell goodsImagesCell2 = row.getCell(18);
                        if(null != goodsImagesCell2 && !ExcelsUtil.isHttpUrl(goodsImagesCell2)) {
                            importMap.put("2", ExcelsUtil.getValue(goodsImagesCell2));
                        }
                        Cell goodsImagesCell3 = row.getCell(19);
                        if(null != goodsImagesCell3 && !ExcelsUtil.isHttpUrl(goodsImagesCell3)) {
                            importMap.put("3", ExcelsUtil.getValue(goodsImagesCell3));
                        }
                        Cell goodsImagesCell4 = row.getCell(20);
                        if(null != goodsImagesCell4 && !ExcelsUtil.isHttpUrl(goodsImagesCell4)) {
                            importMap.put("4", ExcelsUtil.getValue(goodsImagesCell4));
                        }
                        Cell goodsImagesCell5 = row.getCell(21);
                        if(null != goodsImagesCell5 && !ExcelsUtil.isHttpUrl(goodsImagesCell5)) {
                            importMap.put("5", ExcelsUtil.getValue(goodsImagesCell5));
                        }
                        List<Cell> goodsImageCells = new ArrayList<>();
                        goodsImageCells.add(goodsImagesCell1);
                        goodsImageCells.add(goodsImagesCell2);
                        goodsImageCells.add(goodsImagesCell3);
                        goodsImageCells.add(goodsImagesCell4);
                        goodsImageCells.add(goodsImagesCell5);
                        List<GdbMerchantGoodsImagesVO> goodsImages = setGoodsImages(goodsImageCells);
                        if (null != goodsImages && !goodsImages.isEmpty()
                                && StringUtils.isNotEmpty(goodsImages.get(0).getImagesImage())) {
                            // 设置主图，默认第一张图片
                            commonRecord.setCommonImage(goodsImages.get(0).getImagesImage());
                            importGoodsData.setGoodsImages(goodsImages);
                        } else {
                            // 当前行主图为空，取历史的spu上面的主图,历史存储的主图 也为空包错误
                            if (null != goodsCommonMap.get(codeNumber)) {
                                ImportGoodsDataBeanVO oldRecord = goodsCommonMap.get(codeNumber);
                                // 存在 但主图为空
                                if (null != oldRecord.getGdbMerchantGoodsCommon() && StringUtils
                                        .isEmpty(oldRecord.getGdbMerchantGoodsCommon().getCommonImage())) {
                                    errorRow.add("商品图片1;商品图片1不能为空");
                                }
                                // common为空，也需要报错
                                if (null == oldRecord.getGdbMerchantGoodsCommon()) {
                                    errorRow.add("商品图片1;商品图片1不能为空");
                                }
                            } else {
                                errorRow.add("商品图片1;商品图片1不能为空");
                            }
                        }
                        List<GdbMerchantGoodsImagesVO> copyGoodsImages = new ArrayList<>();
                        for (GdbMerchantGoodsImagesVO image : goodsImages) {
                            if (StringUtil.isNotEmpty(image.getImagesImage())) {
                                if(ExcelsUtil.isHttpUrl(image.getImagesImage())) {
                                    copyGoodsImages.add(image);
                                }
                            }
                        }
                        if(!copyGoodsImages.isEmpty()) {
                            importGoodsData.setGoodsImages(copyGoodsImages);
                        }
                        // 这里是商品详情页 也是需要保存到oss上面的 商品详情页 图片内容
                        Cell commonDetailCell1 = row.getCell(22);
                        if(null != commonDetailCell1 && !ExcelsUtil.isHttpUrl(commonDetailCell1)) {
                            importMap.put("6", ExcelsUtil.getValue(commonDetailCell1));
                        }
                        Cell commonDetailCell2 = row.getCell(23);
                        if(null != commonDetailCell2 && !ExcelsUtil.isHttpUrl(commonDetailCell2)) {
                            importMap.put("7", ExcelsUtil.getValue(commonDetailCell2));
                        }
                        Cell commonDetailCell3 = row.getCell(24);
                        if(null != commonDetailCell3 && !ExcelsUtil.isHttpUrl(commonDetailCell3)) {
                            importMap.put("8", ExcelsUtil.getValue(commonDetailCell3));
                        }
                        Cell commonDetailCell4 = row.getCell(25);
                        if(null != commonDetailCell4 && !ExcelsUtil.isHttpUrl(commonDetailCell4)) {
                            importMap.put("9", ExcelsUtil.getValue(commonDetailCell4));
                        }
                        Cell commonDetailCell5 = row.getCell(26);
                        if(null != commonDetailCell5 && !ExcelsUtil.isHttpUrl(commonDetailCell5)) {
                            importMap.put("10", ExcelsUtil.getValue(commonDetailCell5));
                        }
                        List<Cell> commonDetailCells = new ArrayList<>();
                        commonDetailCells.add(commonDetailCell1);
                        commonDetailCells.add(commonDetailCell2);
                        commonDetailCells.add(commonDetailCell3);
                        commonDetailCells.add(commonDetailCell4);
                        commonDetailCells.add(commonDetailCell5);
                        Map<String, String> commonDetailMap = setGdbMerchantGoodsCommonDetailMap(commonDetailCells);
                        String imageHttpUrl = commonDetailMap.get("httpUrl");


                        // http商详链接
                        if(StringUtils.isNotEmpty(imageHttpUrl)) {
                            importGoodsData.setImageName(imageHttpUrl);
                        }
                    } else {
                        errorRow.add("规格类型;规格类型不能为空");
                    }
                    // spu 错误
                    if (errorRow.isEmpty()) {
                        if (null == importGoodsData.getGdbMerchantGoodsCommon()) {
                            importGoodsData.setGdbMerchantGoodsCommon(commonRecord);

                        }

                        if (!importMap.isEmpty()) {
                            flag = true;
                            String jsonMap = JSONObject.toJSONString(importMap);
                            jsonMap = jsonMap.replace(";", ",");
                            logger.info("不是图片url的json字符串："+jsonMap);

                            if (importGoodsData.getGdbMerchantGoodsCommon().getImportNumber()==null){
                                importGoodsData.getGdbMerchantGoodsCommon().setImportNumber(jsonMap);
                            }else{
                                StringBuffer sb = new StringBuffer();
                                sb.append(importGoodsData.getGdbMerchantGoodsCommon().getImportNumber());
                                sb.append(jsonMap);
                                importGoodsData.getGdbMerchantGoodsCommon().setImportNumber(sb.toString());
                            }
                        }

                    }
                    GdbMerchantGoodsBaseVO recordGoodsBase = new GdbMerchantGoodsBaseVO();
                    if (StringUtils.isNotEmpty(goodsName)) {
                        recordGoodsBase.setGoodsName(goodsName);
                    }
                    // 商家编号
                    Cell merchantCodeCell = row.getCell(3);
                    String merchantCodeStr = ExcelsUtil.getValue(merchantCodeCell);
                    if (StringUtils.isNotEmpty(merchantCodeStr)) {
                        recordGoodsBase.setMerchantCode(merchantCodeStr);
                    }
                    // 商品条型码
                    Cell commodityBarTypeCodeCell = row.getCell(4);
                    String commodityBarTypeCodeCellStr = ExcelsUtil.getValue(commodityBarTypeCodeCell);
                    if (StringUtils.isNotEmpty(commodityBarTypeCodeCellStr)) {
                        recordGoodsBase.setCommodityBarTypeCode(commodityBarTypeCodeCellStr);
                    }
                    // 商品重量(kg) 6
                    Cell goodsCubageCell = row.getCell(6);
                    String goodsCubageStr = ExcelsUtil.getValue(goodsCubageCell);
                    if (StringUtils.isNotEmpty(goodsCubageStr)) {
                        if (MathUtil.checkNumber(goodsCubageStr)) {
                            BigDecimal goodsCubage = new BigDecimal(goodsCubageStr);
                            recordGoodsBase.setGoodsCubage(goodsCubage);
                        } else {
                            errorRow.add("商品重量;商品重量格式不正确");
                        }

                    } else {
                        errorRow.add("商品重量;商品重量不能为空");
                    }
                    // 体积（m3） 7
                    Cell goodsVolumeCell = row.getCell(7);
                    String goodsVolumeStr = ExcelsUtil.getValue(goodsVolumeCell);
                    if (StringUtils.isNotEmpty(goodsVolumeStr)) {
                        if (MathUtil.checkNumber(goodsVolumeStr)) {
                            BigDecimal goodsVolume = new BigDecimal(goodsVolumeStr);
                            recordGoodsBase.setGoodsVolume(goodsVolume);
                        } else {
                            errorRow.add("体积（m3）;体积（m3）格式不正确");
                        }
                    } else {
                        errorRow.add("体积（m3）;体积（m3）不能为空");
                    }
                    // 佣金
                    Cell commissionCell = row.getCell(8);
                    String commissionStr = ExcelsUtil.getValue(commissionCell);
                    BigDecimal commission = BigDecimal.ZERO;
                    if (StringUtils.isNotEmpty(commissionStr)) {
                        if (MathUtil.checkNumber(commissionStr)) {
                            commission = new BigDecimal(commissionStr);
                        } else {
                            errorRow.add("佣金;佣金类型不正确");
                        }
                    }
                    recordGoodsBase.setCommission(commission);

                    // 成本价（供货价） 9
                    Cell goodsCostPriceCell = row.getCell(9);
                    String goodsCostPriceStr = ExcelsUtil.getValue(goodsCostPriceCell);
                    if (StringUtils.isNotEmpty(goodsCostPriceStr)) {
                        if (MathUtil.checkNumber(goodsCostPriceStr)) {
                            BigDecimal goodsCostPrice = new BigDecimal(goodsCostPriceStr);
                            recordGoodsBase.setGoodsCostPrice(goodsCostPrice);
                        } else {
                            errorRow.add("成本价（供货价）;成本价（供货价）格式不正确");
                        }
                    } else {
                        errorRow.add("成本价（供货价）;成本价（供货价）不能为空");
                    }
                    // sku市场价格
                    BigDecimal goodsMarketPrice = BigDecimal.ZERO;
                    // 商品价格（直播价）
                    BigDecimal goodsPrice = BigDecimal.ZERO;
                    // 商品价格（直播价） 10
                    Cell goodsPriceCell = row.getCell(10);
                    String goodsPriceStr = ExcelsUtil.getValue(goodsPriceCell);
                    if (StringUtils.isNotEmpty(goodsPriceStr)) {
                        if (MathUtil.checkNumber(goodsPriceStr)) {
                            goodsPrice = new BigDecimal(goodsPriceStr);
                            recordGoodsBase.setGoodsPrice(goodsPrice);
                        } else {
                            errorRow.add("商品价格（直播价）;成本价（供货价）格式不正确");
                        }

                    } else {
                        errorRow.add("商品价格（直播价）;成本价（供货价）不能为空");
                    }
                    // 市场价（销售价） 9
                    Cell goodsMarketPriceCell = row.getCell(11);
                    String goodsMarketPriceStr = ExcelsUtil.getValue(goodsMarketPriceCell);
                    if (StringUtils.isNotEmpty(goodsMarketPriceStr)) {
                        if (MathUtil.checkNumber(goodsMarketPriceStr)) {
                            goodsMarketPrice = new BigDecimal(goodsMarketPriceStr);
                            recordGoodsBase.setGoodsMarketPrice(goodsMarketPrice);
                        } else {
                            errorRow.add("市场价（销售价）;市场价（销售价）格式不正确");
                        }

                    } else {
                        errorRow.add("市场价（销售价）;市场价（销售价）不能为空");
                    }
                    if (!goodsMarketPrice.equals(BigDecimal.ZERO) && !goodsPrice.equals(BigDecimal.ZERO)
                            && goodsPrice.compareTo(goodsMarketPrice) >= 0) {
                        errorRow.add("商品价格（直播价）不能 高于 市场价（销售价）");
                    }
                    // 商品库存 10
                    Cell goodsStockCell = row.getCell(12);
                    String goodsStockStr = ExcelsUtil.getValue(goodsStockCell);
                    if (StringUtils.isNotEmpty(goodsStockStr)) {
                        if (MathUtil.checkNumber(goodsStockStr)) {
                            recordGoodsBase.setGoodsStock(Integer.parseInt(goodsStockStr));
                        } else {
                            errorRow.add("商品库存;商品库存 格式不正确");
                        }
                    } else {
                        errorRow.add("商品库存;商品库存不能为空");
                    }
                    // 销售规格值 12
                    Cell goodsSpecCell = row.getCell(14);
                    String goodsSpecStr = ExcelsUtil.getValue(goodsSpecCell);
                    if (StringUtils.isNotEmpty(goodsSpecStr)) {
                        recordGoodsBase.setGoodsSpec(goodsSpecStr);
                        if (null != importGoodsData.getGdbMerchantGoodsCommon()) {
                            // 开始拼接 spec_value
                            String specParamJson = importGoodsData.getGdbMerchantGoodsCommon().getSpecParam();
                            if (StringUtils.isNotEmpty(specParamJson)) {
                                Map<String, String> tempMap = getSpecValueMap(goodsSpecStr, specParamJson);
                                if (null != tempMap.get("error") && StringUtils.isNotEmpty(tempMap.get("error"))) {
                                    errorRow.add("销售规格值;销售规格和规格类型数量不一致");
                                    errorSpec.add(codeNumber);
                                } else {
                                    if (StringUtils.isNotEmpty(tempMap.get("specParamJsonObject"))) {
                                        importGoodsData.getGdbMerchantGoodsCommon()
                                                .setSpecParam(tempMap.get("specParamJsonObject"));
                                    }
                                    if (StringUtils.isNotEmpty(tempMap.get("goodBaseSpecValuesJsonBean"))) {
                                        recordGoodsBase.setSpecValue(tempMap.get("goodBaseSpecValuesJsonBean"));
                                    }
                                }
                            }
                        }
                    } else {
                        errorRow.add("销售规格值;销售规格值不能为空");
                    }

                    //TODO 是否寄回样品  15  sendBack 0：是 1:否 -whx
                    Cell goodsSendBackCell = row.getCell(15);
                    String goodsSendBackStr = ExcelsUtil.getValue(goodsSendBackCell);
                    if (StringUtils.isNotEmpty(goodsSendBackStr)) {
                        if (MathUtil.checkSendBack(goodsSendBackStr)) {
                            //默认为0，
                            Integer sendBackNum =0;
                            if ("否".equals(goodsSendBackStr)){
                                sendBackNum=1;
                            }
                            recordGoodsBase.setGoodsSendBack(sendBackNum);
                        } else {
                            errorRow.add("是否寄回样品;是否寄回样品 格式不正确");
                        }
                    } else {
                        errorRow.add("是否寄回样品;是否寄回样品不能为空");
                    }
                    Cell sellingPointCell = row.getCell(16);
                    String sellingPointStr = ExcelsUtil.getValue(sellingPointCell);
                    if (StringUtils.isNotEmpty(sellingPointStr)) {
                        if (sellingPointStr.length() > 3000) {
                            errorRow.add("直播卖点介绍;直播卖点介绍输入的内容不能超过3000个字符");
                        } else {
                            recordGoodsBase.setSellingPoint(sellingPointStr);
                        }
                    }
                    // 刚开始，goodsbase 为null,需要创建设置
                    if (null == importGoodsData.getGdbMerchantGoodsBases()) {
                        importGoodsData.setGdbMerchantGoodsBases(new ArrayList<GdbMerchantGoodsBaseVO>());
                    }
                    // sku 里面不加入
                    if (errorRow.isEmpty() && !errorSpec.contains(codeNumber)) {
                        List<GdbMerchantGoodsBaseVO> gdbMerchantGoodsBase = importGoodsData.getGdbMerchantGoodsBases();
                        gdbMerchantGoodsBase.add(recordGoodsBase);
                        importGoodsData.setGdbMerchantGoodsBases(gdbMerchantGoodsBase);
                        goodsCommonMap.put(codeNumber, importGoodsData);
                    }
                }
                if (!errorRow.isEmpty()) {
                    errorMsg.put(i, errorRow);
                    logger.info("row number =" + i + JSON.toJSONString(errorRow));
                }
            }
            // 删除规格 数量 不匹配已经加入到map里面的
            for (String number : errorSpec) {
                List<Integer> errorNumberRows = codeNumberRow.get(number);
                if (null != errorNumberRows && !errorNumberRows.isEmpty()) {
                    for (Integer errorNumberRow : errorNumberRows) {
                        if (null != errorMsg.get(errorNumberRow)) {
                            List<String> msg = errorMsg.get(errorNumberRow);
                            if(null == msg || msg.isEmpty()) {
                                msg = new ArrayList<String>();
                            }
                            msg.add("规格类型;规格类型不正确");
                            errorMsg.put(errorNumberRow, msg);
                        } else {
                            List<String> msg = errorMsg.get(errorNumberRow);
                            if (null == msg || msg.isEmpty()) {
                                msg = new ArrayList<String>();
                            }
                            msg.add("规格类型;规格类型不正确");
                            errorMsg.put(errorNumberRow, msg);
                        }
                    }
                }
                goodsCommonMap.remove(number);
            }
            // 删除主图重复的
            for (String number : errorMainImages) {
                goodsCommonMap.remove(number);
            }
            // 根据错误信息删除所有错误的spu
            errorMsg.forEach((key, value) -> {
                Integer rowNumber = (Integer) key;
                Row errorRow = sheet.getRow(rowNumber);
                if (null != errorRow && errorRow.getPhysicalNumberOfCells() != 0 && null != errorRow.getCell(0)) {
                    String errorCodeNumber = ExcelsUtil.getValue(errorRow.getCell(0));
                    if (StringUtils.isNotEmpty(errorCodeNumber) && goodsCommonMap.containsKey(errorCodeNumber)) {
                        goodsCommonMap.remove(errorCodeNumber);
                    }
                }
            });
            resultMap.put("goodsCommonMap", goodsCommonMap);
            resultMap.put("errorMsg", errorMsg);
            resultMap.put("isUploadUnzip", flag);
            return resultMap;
        }
        return null;
    }

    /**
     * 拼接common表中的 spec_param 和 base 表中的 spec_value
     *
     * @param goodsSpecStr
     * @param specParamJson
     * @return
     */
    public Map<String, String> getSpecValueMap(String goodsSpecStr, String specParamJson) {
        Map<String, String> result = new HashMap<>();
        String[] goodsSpeces = goodsSpecStr.split("\\+");
        JSONArray specParamJsonObject = (JSONArray) JSON.parse(specParamJson);
        List<GoodBaseSpecValuesJsonBeanVO> records = new ArrayList<>();
        List<SpecParamJsonBeanVO> resultSpecParamJsonBean = new ArrayList<>();
        if (specParamJsonObject.size() != goodsSpeces.length) {
            result.put("error", "规格和规格值数量不相等");
            return result;
        }
        for (int index = 0; index < goodsSpeces.length; index++) {
            List<String> paramNameValues = null;
            JSON specParamJSON = (JSON) specParamJsonObject.get(index);
            SpecParamJsonBeanVO specParam = JSON.parseObject(specParamJSON.toJSONString(), SpecParamJsonBeanVO.class);
            if (null != specParam.getParamNameValues()) {
                paramNameValues = specParam.getParamNameValues();
            } else {
                paramNameValues = new ArrayList<>();
            }
            String goodsSpec = goodsSpeces[index];
            if (!paramNameValues.contains(goodsSpec)) {
                paramNameValues.add(goodsSpec);
            }
            specParam.setParamNameValues(paramNameValues);
            resultSpecParamJsonBean.add(specParam);
            GoodBaseSpecValuesJsonBeanVO record = new GoodBaseSpecValuesJsonBeanVO();
            if (StringUtils.isNotEmpty(specParam.getParamName())) {
                record.setParamName(specParam.getParamName());
            }
            if (null != specParam.getIsCommon()) {
                record.setIsCommon(specParam.getIsCommon());
            }
            if (null != specParam.getRefSpecId()) {
                record.setRefSpecId(specParam.getRefSpecId());
            }
            record.setParamValue(goodsSpec);
            records.add(record);
        }
        result.put("specParamJsonObject", JSON.toJSONString(resultSpecParamJsonBean));
        result.put("goodBaseSpecValuesJsonBean", JSON.toJSONString(records));
        return result;
    }



    /**
     * 设置商品详情页
     *
     * @param cells
     * @return
     */
    public Map<String, String> setGdbMerchantGoodsCommonDetailMap(List<Cell> cells) {
        Map<String, String> result = new HashMap<String, String>();
        String httpUrl = "";
        String imageName = "";
        if (null != cells && !cells.isEmpty()) {
            for (Cell cell : cells) {
                String path = ExcelsUtil.getValue(cell);
                if(path.startsWith("http://") || path.startsWith("https://")) {
                    httpUrl += path + ";";
                } else {
                    imageName += path + ";";
                }
            }
        }
        result.put("httpUrl", httpUrl);
        result.put("imageName", imageName);
        return result;
    }



    /**
     * 设置商品图片 在商品详情页 图片列表
     *
     * @param cells
     * @return
     */
    public List<GdbMerchantGoodsImagesVO> setGoodsImages(List<Cell> cells) {
        if (null != cells && !cells.isEmpty()) {
            List<GdbMerchantGoodsImagesVO> goodsImages = new ArrayList<>();
            for (Cell cell : cells) {
                String path = ExcelsUtil.getValue(cell);
                GdbMerchantGoodsImagesVO recordImage = new GdbMerchantGoodsImagesVO();
                recordImage.setImagesDisplayorder(0);
                recordImage.setImagesIsDefault(1);
                recordImage.setImagesImage(path);
                goodsImages.add(recordImage);
            }
            return goodsImages;
        }
        return null;
    }



    /**
     * 导入zip文件进行OSS上传
     * @param mapByte
     * @return
     */
    public Map<String,Map<String,Object>> importUploadOSS(Map<String, byte[]> mapByte,List<String> commonList){

        Map<String,Map<String,Object>> mapOut =new HashMap<>();
        //遍及入参的CommonList
        for (int i = 0; i < commonList.size(); i++) {
            System.out.println(commonList.get(i));
            String imageName =null;
            Integer commonId =Integer.valueOf(commonList.get(i));
            imageName=this.baseMapper.selectById(commonId).getImportNumber();
            Map<String,Object> paramMap =new HashMap<>();
            if(org.apache.commons.lang.StringUtils.isNotEmpty(imageName)) {
                Map<String,String> imagesNameList = JsonUtils.string2Obj(imageName, Map.class);
                System.out.println(imagesNameList);
                //获取对应commonID下的图片名称并且转换成List
                List<String> listString = new ArrayList<>();

                Iterator<String> iter = imagesNameList.keySet().iterator();
                while (iter.hasNext()) {
                    String image = imagesNameList.get(iter.next());
                    listString.add(image);
                }

                for (int j = 0; j < listString.size(); j++) {
                    //获取图片名
                    String pictureName=listString.get(j);

                    if (mapByte != null){
                        //遍历map
                        for(String key:mapByte.keySet()){
                            StringBuffer prefixName = new StringBuffer();
                            prefixName.append("https:");
                            logger.info("importUploadOSS[]Key: "+key+" Value: "+mapByte.get(key));

                            String photoName=key.substring(key.indexOf("/")+1,key.length());
                            logger.info("photoName{}"+photoName);

                            if (pictureName.equals(photoName)){
                                OssUploadUpdateParamDTO ossUploadUpdateParam = new OssUploadUpdateParamDTO();
                                ossUploadUpdateParam.setBase64Str(Base64.getEncoder().encodeToString(mapByte.get(key)));
                                ossUploadUpdateParam.setStreamName(photoName);
                                ResponseResult resp = uploadToOss(ossUploadUpdateParam);

                                String  ossImageUrl = null;
                                ossImageUrl = resp.getData().toString();

                                logger.debug("uploadImgUrl result ossImageUrl:{}",ossImageUrl);
                                logger.info("uploadImgUrl result ossImageUrl:{}",ossImageUrl);


                                paramMap.put(key,ossImageUrl);


                            }

                        }
                    }

                }

            }

            mapOut.put(String.valueOf(commonId),paramMap);
        }

        //进行数据库业务操作
        this.updateImagesCommon(mapOut);
        return mapOut;
    }


    /**
     * 业务代码操作
     * @param map
     */
    @Transactional
    public void updateImagesCommon(Map<String,Map<String,Object>> map){

        if (map != null){
            Map<String,Object> mapList = new HashMap<>();
            for (String key:map.keySet()){

                //清空gdb_merchant_goods_images 表
                goodsImagesMapper.delete(new LambdaQueryWrapper<GoodsImagesEntity>().eq(GoodsImagesEntity::getCommonId, Integer.valueOf(key)));
                Map<String,Object> varMap =map.get(key);
                for (String varKey:varMap.keySet()){

                    String imageCode=varKey.substring(varKey.indexOf(".")-3,varKey.indexOf("."));
                    logger.info("imageCode{}"+imageCode);
                    Map<String,Object> masterMapParam = new HashMap<>();
                    String commonId=key;
                    logger.info("commonId{}"+commonId);
                    logger.info("imageUrl{}"+varMap.get(varKey));
                    GoodsImagesEntity entity=new GoodsImagesEntity();
                    entity.setCommonId(Integer.valueOf(commonId));
                    entity.setImagesImage(varMap.get(varKey).toString());

                    if (imageCode.contains("001")){
                        logger.info("主图操作");

                        //更新 gdb_merchant_goods_common 表
                        this.baseMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                                       .eq(GoodsCommonEntity::getCommonId,commonId)
                                       .set(GoodsCommonEntity::getCommonImage,varMap.get(varKey)));
                        //更新 gdb_merchant_goods_base 表
                        goodsBaseMapper.update(null,new LambdaUpdateWrapper<GoodsBaseEntity>()
                                        .eq(GoodsBaseEntity::getCommonId,commonId)
                                        .set(GoodsBaseEntity::getGoodsImage,varMap.get(varKey)));

                        Integer shopId =0;
                        shopId=this.baseMapper.selectById(Integer.valueOf(commonId)).getShopId();



                        entity.setShopId(Integer.valueOf(shopId));
                        //插入gdb_merchant_goods_images 表
                        goodsImagesMapper.insert(entity);



                    }else if (imageCode.contains("002")){

                        Integer shopId =0;
                        shopId=this.baseMapper.selectById(Integer.valueOf(commonId)).getShopId();
                        entity.setShopId(Integer.valueOf(shopId));
                        //插入gdb_merchant_goods_images 表
                        goodsImagesMapper.insert(entity);

                    }else if (imageCode.contains("003")){
                        Integer shopId =0;
                        shopId=this.baseMapper.selectById(Integer.valueOf(commonId)).getShopId();
                        entity.setShopId(Integer.valueOf(shopId));
                        //插入gdb_merchant_goods_images 表
                        goodsImagesMapper.insert(entity);

                    }else if (imageCode.contains("004")){
                        Integer shopId =0;
                        shopId=this.baseMapper.selectById(Integer.valueOf(commonId)).getShopId();
                        entity.setShopId(Integer.valueOf(shopId));
                        //插入gdb_merchant_goods_images 表
                        goodsImagesMapper.insert(entity);

                    }else if (imageCode.contains("005")){
                        Integer shopId =0;
                        shopId=this.baseMapper.selectById(Integer.valueOf(commonId)).getShopId();
                        entity.setShopId(Integer.valueOf(shopId));
                        //插入gdb_merchant_goods_images 表
                        goodsImagesMapper.insert(entity);

                    } else {

                        logger.info("详情图操作");
                        if (org.springframework.util.StringUtils.isEmpty(mapList.get(commonId))){
                            mapList.put(commonId,"<p><img class=\"wscnph\" src=\"".concat(varMap.get(varKey).toString()).concat("\" />"));

                        }else {
                            //取出已经存在的url值
                            String imagesUrl = mapList.get(commonId).toString();
                            mapList.put(commonId,imagesUrl.concat("<p><img class=\"wscnph\" src=\"").concat(varMap.get(varKey).toString()).concat("\" />"));
                        }

                    }

                }


            }
            if (mapList.size()>0){
                //遍历map
                for(String key:mapList.keySet()) {
                    Map<String,Object> mapOut = new HashMap<>();
                    logger.info("Key: " + key + " Value: " + mapList.get(key));
                    Integer count =0;

                    //查询gdb_merchant_goods_common_detail是否已经存在数据
                    count=goodsCommonDetailMapper.selectCount(new LambdaQueryWrapper<GoodsCommonDetailEntity>()
                                                 .eq(GoodsCommonDetailEntity::getCommonId,Integer.valueOf(key)));

                    mapOut.put("common_id", Integer.valueOf(key));
                    mapOut.put("imageUrl", mapList.get(key));
                    if (count >0) {
                        //更新gdb_merchant_goods_common_detail表
                        goodsCommonDetailMapper.update(null,new LambdaUpdateWrapper<GoodsCommonDetailEntity>()
                                                .set(GoodsCommonDetailEntity::getCommonBody,mapList.get(key).toString())
                                                .eq(GoodsCommonDetailEntity::getCommonId, Integer.valueOf(key)));
                    }else {
                        //插入gdb_merchant_goods_common_detail表
                        GoodsCommonDetailEntity entity=new GoodsCommonDetailEntity();
                        entity.setCommonId(Integer.valueOf(key));
                        entity.setCommonBody(mapList.get(key).toString());
                        goodsCommonDetailMapper.insert(entity);
                    }

                }

            }
        }

    }


    /**
     * 根据三级类目 获取common 表里面的 cat_name
     *
     * @param threadCatId
     * @return
     */
    public Map<String, Object> getCatName(Integer threadCatId) {
        Map<String, Object> result = new HashMap<>();
        GoodsCatEntity threedCat = goodsCatMapper.selectById(threadCatId);
        if (null != threedCat) {
            result.put("threedCat", threedCat);
            GoodsCatEntity sendCat = goodsCatMapper.selectById(threedCat.getCatParentId());
            if (null != sendCat) {
                result.put("sendCatId", sendCat.getCatId());
                GoodsCatEntity firstCat = goodsCatMapper.selectById(sendCat.getCatParentId());
                if (null != firstCat) {
                    result.put("catName",
                            firstCat.getCatName() + ">" + sendCat.getCatName() + ">" + threedCat.getCatName());
                }
            }
        }
        return result;
    }




    /**
     * oss上传
     * @param param
     * @return
     */
    public ResponseResult uploadToOss(OssUploadUpdateParamDTO param) {
        param.setFileUrl("file/upload/shop/settled/");
        //获取OSS配置文件中的阿里云API的外网域名
        ResponseResult resultResp=baseServiceClient.selectOSSInfo();
        Map<String,Object> map = (Map<String,Object>)resultResp.getData();
        param.setEndpoint(map.get("ossFolder").toString());
        return thirdPartyServiceClient.uploadToOssBase64(param);
    }




    //取出catId
    public List<Integer> catIds(List<WebCatMenuVO>  WebCatMenus){
        List<Integer> catIds = new ArrayList<>();
        for (WebCatMenuVO webCatMenu : WebCatMenus) {
            catIds.add(webCatMenu.getCatId());
        }
        return catIds;
    }
}

